title: How can you link Parallel Mapping and Error tracking

text: Following this question and the comments made, together with the information in this question, the following code allows error tracking and debugging very nicely.               SetAttributes[withTaggedMsg, HoldAll];          withTaggedMsg[sym_] := Function[,       Internal`InheritedBlock[{MessagePacket},         Unprotect[MessagePacket];         MessagePacket[name__, BoxData[obj_, form_]] /; ! TrueQ[$tagMsg] :=               Block[{$tagMsg = True},             Identity@MessagePacket[name, BoxData[RowBox[{               ToBoxes @ Style[                 Row[{"At iteration", HoldForm[sym], "=", sym, Spacer[5]}, " "],                 Black],             obj}], form]]           ];         #       ], HoldAll];          f[var : _] :=         Block[{arg},         arg = var;         1/arg     ];          Map[f[#] &, Range[-2, 1, 1]] // withTaggedMsg[arg]          (*At iteration arg=0  Power::infy : Infinity expression 1/0 encountered.     {-(1/2), -1, ComplexInfinity, 1}*)      Now, the big problem is **how to use`withTaggedMsg` together with `ParallelMap`** instead of `Map`.               ParallelMap[f[#] &, Range[-2, 1, 1]] // withTaggedMsg[arg]          (*At iteration arg=arg Parallel`Protected`PacketHandler::default: Unhandled packet MessagePacket[Power,infy,BoxData[RowBox[{StyleBox[RowBox[{Power,::,infy}],     MessageName],: ,"Infinite expression \!\(1\/0\) encountered."}],StandardForm]] received and discarded from KernelObject[6,local].     {-(1/2), -1, ComplexInfinity, 1}*)      I don't see how I could do it, and would appreciate immensely if I could get some input in this. Thanks!


title: How to code the following product?

text: I am trying to examine the properties of the following product for a given tuple $\vec \lambda = (\lambda_1, \lambda_2, \dots, \lambda_n)$, then the product is as follows: $$ \dim \Gamma_\lambda = \prod_{i < j} {(l_i^2 - l_j^2) \over (m_i^2 - m_j^2)} = 2^{n-1} {\prod_{i < j} (l_i^2 - l_j^2) \over (2n - 2)!\cdot (2n - 4)! \cdots 2!} $$ where $l_i = \lambda_i +n - i$ and $m_i = n- i$. The function `dim_calc(n, lambda)` might take a tuple `lambda` and the length of the tuple, `n`, and then define the $l_i$ and $m_i$'s accordingly? I'm not really sure how to write this though...any hints for this symbolic computation? Thanks!


title: Duplex Printing from button inside DialogNotebook on Mac

text: All, I have the following code which generates a window containing the variable _PrintOut_ and a Print button. When the print button is pressed the contents of the window are sent to the printer and simultaneously a pdf is generated.               PrintOut = "Some stuff - plots, tables etc.";          DialogInput[       DialogNotebook[        Column[{PrintOut,           Row[{Button["Print",              DialogReturn[NotebookPrint[PrintOut, "filename.pdf"];              NotebookPrint[               CreateDocument[PrintOut, Visible -> False,                 PageHeaders -> {{"a", "b", DateString[]}, {"a", "b",                    DateString[]}}]]]], CancelButton[]}]}]],        ShowStringCharacters -> False,        WindowTitle -> "This Window " <> DateString[]];      The problem arises when _PrintOut_ contains enough stuff to be spread over multiple pages. I wish to have the pages print on both sides but can't figure out how to do it. I have the print settings within MMA set to duplex and when I print a notebook using the front end I get duplex but it does not work for DialogNotebook. I am using MMA8 Help appreciated.


title: Installing R packages using RLink on Mac OS X

text: Is there any updates regarding installing CRAN packages via RLink in Mathematica 10 on Mac OS X? Or are we still stuck with the base R package and that's it? I was able to point to my R distribution using this answer but using external packages led to errors. Here is my code:               Needs["RLink`"]     SetEnvironment[     "DYLD_LIBRARY_PATH" ->      "/Library/Frameworks/R.Framework/Resources/lib"];          InstallR["RHomeLocation" ->      "/Library/Frameworks/R.Framework/Resources"];          REvaluate["R.version.string"]          REvaluate["library(GA)"]          REvaluate["f <- function(x)  abs(x)+cos(x)                fitness <- function(x) -f(x)                ga(type='real-valued',fitness=fitness,min=-20,max=20)                summary(GA)"]          Out[15]= $Failed      and the error message:               REvaluate::rerr: Failed to retrieve the value for variable or piece of code f<- function(x)  abs(x)+cos(x)     fitness <- function(x) -f(x)     ga(type='real-valued',fitness=fitness,min=-5,max=5)     summary(GA). The following R error was encountered: Error in typeof(myRandomVar123456740025) :      object 'myRandomVar123456740025' not found >>


title: Help understanding overloading of Atomics within Block

text: Usually `h @@@ {f[1, 2], f[3, 4]} === {h[1, 2], h[3, 4]}` but this is not the case when `f` is `Complex`: `h @@@ {1 + 2I, 3 + 4I } === {1 + 2 I, 3 + 4 I}` Since `Complex`is an atomic and as documentation for `Apply` states: _Applying to atomic objects that do not have subparts effectively does nothing_ Using `Block` to replace `Complex` with `complex` gives result as expected for non-atomic case:               Block[{Complex = complex},      List @@@ {Complex[1, 2], Complex[3, 4]}      ]     (* {{1, 2}, {3, 4}} *)      But then how come replacing `Complex` with `List` while not `Apply`-ing does not give the same result?               Block[{Complex = List},      {Complex[1, 2], Complex[3, 4]}      ]     (* {Complex[1, 2], Complex[3, 4]} *)      As it would have for a non-atomic head:               Block[{f = List},      {f[1, 2], f[3, 4]}      ]     (* {{1, 2}, {3, 4}} *)


title: Gridlines of a framed plot with a background cannot be white?

text: Looking at this question, I am reminded of a problem that I was never able to solve with obtaining a particular plot format. The issue is that `GridLines` sit _behind_ anything in `Prolog`. You can have gridlines with a colored background by giving the background a non-zero `Opacity`.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic}]      ![enter image description here](http://i.stack.imgur.com/OkpGL.png) But if the gridlines are to be white, this isn't feasible, it seems.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic},        GridLinesStyle -> Directive[AbsoluteThickness[2], White]]      ![enter image description here](http://i.stack.imgur.com/3aeVP.png) Yes, you can use the undocumented option `Method -> {"GridLinesInFront" -> True}`, as described in this answer, but then the gridlines go on top of the plot line as well as the background.               Framed@Plot[Sin[x], {x, 0, 2 \[Pi]}, Frame -> True,        Prolog -> {LightGray, Opacity[0.5],          Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},        GridLines -> {None, Automatic},        GridLinesStyle -> Directive[AbsoluteThickness[2], White],        Method -> {"GridLinesInFront" -> True}]      ![enter image description here](http://i.stack.imgur.com/IREBO.png) Is there a way to reorder the `Prolog` background or the gridlines somehow, so that white gridlines shock, but the gridlines don't go over the plotted function? Try as I might I was never able to replicate this format (the axis numbers _inside_ the frame are a whole other question). ![enter image description here](http://i.stack.imgur.com/9REBg.png)


title: Evaluating double Integral

text: While trying to evaluate the integral $\int_{y=0}^{x_2}\int_{x=0}^{min(x_1,y)} n (n - 1) (1 - y)^{(n - 2)}dxdy $ , Mathematica does not seem to yield any results.                Integrate[n (n - 1) (1 - y)^(n - 2), {y, 0, x2}, {x, 0, Min[y, x1]}]      Wolframm alpha also fails saying standard computation time exceeded. Is there anyway to evaluate the integral? I also tried this,               Assuming[0 < x1 < x2 < 1,       Integrate[n (n - 1) (1 - y)^(n - 2), {y, 0, x2}, {x, 0, Min[y, x1]}]]


title: from complex function to a series

text: How can I express this complex function as a series?               Log[      (1 - E^((I Pi (1 - a))/(b - a)) z)/      (1 - E^(-((I Pi (1 - a))/(b - a))) z)     ]      Where `z` is the complex number, `a` and `b` are real numbers, `a < 1` and `b > 1`.


title: Brackets in output make unable to use output to identify matrix element

text: I'm trying to write a code where each matrix element swaps with a randomly selected neighbor (cardinal directions only) to redistribute the matrix. So far I've been able to replace an element with its neighbor, making the elements twins, but I want to preserve the relative amount of "-1"s to "1"s. What you see below is what I have currently, which shows how I identify the neighbors of each element, and how I randomize which one switches with it. The output of this process gives me something in the form of `{i,j}`, which means I can't use `Si[[choice]]`, because that would be effectively saying `Si[[{i,j}]]`, which isn't correct syntax. I'm pretty new to Mathematica, so any help would be greatly appreciated! :) Input:               Si = {{-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}};          Off[General::stop];          ii = 3;         jj = 3;          For[i = 1, i <= ii, i++,      For[j = 1, j <= jj, j++,            choices = {{i, Mod[j - 1, ii, 1]}, {Mod[i - 1, ii, 1], j},          {i, Mod[j + 1, ii, 1]}, {Mod[j - 1, ii, 1], j}};(*identifies neighbors*)            choice = choices[[RandomInteger[{1, 4}]]]; (*randomly chooses a neighbor*)            Si[[i, j]] = choice;(****************)            Print[choices];       Print[choice];       Print[Si]       ]      ]      Output:               {{1,3},{3,1},{1,2},{3,1}}          {3,1}          {{{3, 1}, -1, -1}, {1, -1, -1}, {-1, 1, -1}}          {{1,1},{3,2},{1,3},{1,2}}          {1,2}          {{{3, 1}, {1, 2}, -1}, {1, -1, -1}, {-1, 1, -1}},      etc. and so forth. Okay, so if I replace               Si[[i, j]] = choice;      with               Si[[i, j]] = Extract[Si, choice];       I can get the output to have replaced my original element, but I still don't know how to replace the neighbor with the value of the original element then.


title: Stylesheet modifications mimicking Stack Exchange styles

text: I find myself frequently highlighting and formatting portions of text cells in a _Mathematica_ notebook. Bold and Italic typesetting is easy to handle but I would like to use `backticks` to provide formatting similar to the SE editor or perhaps use underscores and asterisks to auto-format in other ways (say for example, text within ** here ** would be red and text within _ here _ would be highlighted yellow. Is it possible to customize a stylesheet to afford this type of formatting?


title: Mathematica Can't Evaluate This?

text: I am trying to find the inverse function of $\frac{\ln{x}}{x^2}$ in Mathematica. I am using the `Solve[]` function to find the inverse (yes, I know about `InverseFunction[]`, but I was told to solve it with `Solve[]`). Why doesn't the following output evaluate correctly? I know that I shouldn't get imaginary values: ![enter image description here](http://i.stack.imgur.com/OtChM.png) Plugging the equation into `Solve[]` directly also gives me the same result: ![enter image description here](http://i.stack.imgur.com/cB5GZ.png) However, if I drop the `x` from the `Log[]` function, I get something that looks more plausible: ![enter image description here](http://i.stack.imgur.com/FCeK1.png) Does `Log[x]` and `Log` evaluate to the same thing? Thank you for your time!


_**How to get the coordinates of the point that the mouse touch?_** When my mouse touch the picture that the _Mathematica_ touch ,I hope it can return the coordinates?


title: Calculating probabilities symbolically

text: Is there a way to solve for statistical quantities analytically/symbolically in _Mathematica_? **example 1:**   Lets say that I want to do a calculation that requires Bayes theorem. I know p(a), p(b) and p(a | b). I want to calculate p(b | a). Now, for this simple example, I know the solution, so I could write the relationship myself, but what about more complicated examples? Surely _Mathematica_ is able to solve probability problems like it can solve algebraic ones? I want to stay away from simulation. I want _Mathematica_ to do the five pages of math that I normally do on paper. Can _Mathematica_ do this for me? I'd like to type something like               Solve[p(a) == a1 && p(b) == a2 && p(a|b) == a3, p(b|a)]      and get > >     p(b|a) -> (a3*a2)/a1 >   **example 2:**   I want to use the law of total probability: I know `p(a|b)`, `p(a|!b)`, and `p(b)` and I want to calculate `p(a)`. I'd like to type something like               Solve[p(a|b) == a1 && p(a|!b) == a2 && p(b) == a3, p(a)]      and get > >     p(a) -> a1*a3 + a2*(1-a3) >


title: Using CellPrint with a TraditionalForm string

text: I am trying to use CellPrint to print a cell that asks a user to solve an equation. This equation is randomly generated right beforehand, and I would like to have it print in Blue. The whole Cell should be in the "Section" style. Here is my first attempt:               equat = ToString[     Expand[Product[(x - RandomInteger[{-10, 10}]), {i,        3 + RandomInteger[]}]], TraditionalForm];     CellPrint[     Cell[TextData[     RowBox[{StyleBox["Solve the equation "],        StyleBox[equat, FontColor -> Blue]}]], "Section"]];      This does in fact create the cell, and the last part is blue, but it is hindered by the TraditionalForm "markup": I won't put any color here, but the command above gives the output               Solve the equation \!\(TraditionalForm\`\(x\^4 - \(\(73\ x\^2\)\) - \(\(72\ x\)\)\)\)      Is there a simple way to fix this? I have tried using ToBoxes, but then I don't see how to color the output Blue. Any tips or pointers would be much appreciated.


title: Can't force UnitConvert to be evaluated in Plot

text: I'm trying to use new units support in _Mathematica 9_. When I `Plot` `Quantity` functions everything is OK.               v[e_] := Quantity[0.001, "m^3"] e     Plot[Evaluate@v[e], {e, 0, 1}]      But when I `UnitConvert` them, I get only an empty image with axes only.               v1[e_] := UnitConvert[v[e], "Liters"]     Plot[Evaluate@v1[n], {n, 0, 1}]      And no error message at all. By the way, `Plot` likes to do this very much - to draw nothing and not to tell why, and that sucks. Other standard functions seem to be plottable even with `Quantity` arguments.               v2[e_] := Sqrt[v[e]]     Plot[Evaluate@v2[n], {n, 0, 1}]      I can't figure out, what is the difference. The only difference I see is a `NumericFunction` attribute.               In[84]:= Attributes[Sqrt]          Out[84]= {Listable, NumericFunction, Protected}          In[85]:= Attributes[UnitConvert]          Out[85]= {Listable, Protected}      But `Quantity` values aren't numeric themselves, so this shouldn't make difference, should it?               In[1]:= NumericQ[Quantity[1, "L"]]          Out[1]= False      Can anyone explain this, please? Or is it some kind of bug? **EDIT:** I think, I can answer this myself now. As for Plot function, there is no sign in documentation and tutorials that using it with units supported. But there is also no sign that it isn't. Everywhere plotting with units is mentioned with different List*Plot functions. And they work fine with some good features:               v0[e_] := Quantity[0.001, "m^3"] e     es = Range[0, 1, 0.1];     cubes = v0 /@ es;     liters = UnitConvert[cubes, "L"];     ListLinePlot[cubes]     ListLinePlot[Transpose@{es, cubes}, AxesLabel -> Automatic]     ListLinePlot[Transpose@{es, liters}, AxesLabel -> Automatic]      or even               ListLinePlot[Transpose@{es, cubes}, AxesLabel -> Automatic, TargetUnits -> "Litres"]      It seems like Plot supports units, but "not very much". There is no TargetUnits parameter, and AxesLabel -> Automatic doesn't place unit names in labels. But still it can be used somehow. For my case, I found two solutions (thanks to @Anon for one of them and for direction to think to another). This               Plot[Evaluate@UnitConvert[e Quantity[0.001, "Meters"^3], "L"], {e, 0, 1}]      doesn't work. But this               Plot[Evaluate@UnitConvert[Quantity[0.001 e, "Meters"^3], "L"], {e, 0, 1}]      works. And this (a bit esoteric) variant too:               Plot[Evaluate@UnitConvert[Quantity[e, "m/m"] Quantity[0.001, "Meters"^3], "L"], {e, 0, 1}]      The reason for all these troubles may be the fact that Mathematica lacks a "truly" dimensionless units:               In[774]:= Clear[a]          In[775]:= QuantityUnit[a] (* this is OK, we don't know if 'a' has any \     units at all *)     Out[775]= QuantityUnit[a]          In[776]:= (* but we know that 1 doesn't have any *)     QuantityUnit[1]     Out[776]= "DimensionlessUnit"          In[777]:= (* and surely 1m has *)     QuantityUnit[Quantity[1, "m"]]     Out[777]= "Meters"          In[778]:= (* and this ratio is correctly dimensionless *)     QuantityUnit[Quantity[1, "m"]/Quantity[1, "m"]]     Out[778]= "DimensionlessUnit"          (* this ratio is dimensionless by its nature, but it isn't in Mathematica *)     QuantityUnit[Quantity[a, "m"]/Quantity[1, "m"]]     Out[779]= QuantityUnit[a]      The core of the problem seems to be here:               In[780]:= Quantity[Quantity[1, "m"], "m"]     Out[780]= Quantity[1, ("Meters")^2]      According to physics (and common sence) "1 meter of meters" is nonsense. No way it can be 1 square meter.


title: Number of edges to each polygon of a graph constructed from an image

text: I have an image which looks like ![](http://i.stack.imgur.com/cET4A.png) from How to convert an image to a graph and get the positions of the edges? which by using `MorphologicalGraph` becomes a graph that is a collections of polygons:               i = Import["http://i.stack.imgur.com/cET4A.png"];     g = MorphologicalGraph[i,           EdgeStyle -> Directive[Orange, Opacity[.5], Thickness[.01]],          GraphStyle -> "ThickEdge"];     Show[ColorNegate@Dilation[i, 1], g]      I am wondering if, for each polygon, it is possible to extract the number of edges?


title: Why does my attempt at parallelization not work?

text: I want to run some function with different parameters, parallel on 4 cores (i5). When I run it without using `Parallelize`, processor has ~25% utilization. It's a little time consuming (a couple of minutes), so I tried run it 4x with different parameters on each core. I tried: `Parallelize[{f[a1,b1,c1],f[a2,b2,c2],f[a3,b3,c3],f[a4,b4,c4]}]` (also with different methods like: "FinestGrained"/"CoarsestGrained"/"EvaluationsPerKernel" -> 1) and still, total utilization of cpu is 30% top).   1. Each variant is processed within a few minutes, at least 4 minutes.   2. In Parallel Kernel Status window all 4 kernels have status _busy_ , after the start of the calculation. I used Parallelize earlier and it worked just fine (~100% utilization).  So, what is the reason? My configuration: Mathematica 9.0.0/Win8 x64/i5 2500k, 4GB RAM


title: Contour plot doesn't look right

text: I have an implicit function expression               F[x, y] :=        -E^(-2 a) (-1 + (c (1 - 1/y^2))/a)          (-1 + (b (1 - 1/y^2))/(2 a)) + (1 + (c (1 - 1/y^2))/a) (1 + (b (1 - 1/y^2))/(2 a))      where               a = Sqrt[x^2 - (1 - 1/y^2) y^2]          b = Sqrt[x^2 - 2 y^2]          c = Sqrt[x^2 - y^2]      I plot the expression `F[x, y] == 0` with `ContourPlot`, and I get something like this: ![](http://i.stack.imgur.com/t2E41.png) I need to obtain a plot like this: ![](http://i.stack.imgur.com/LrUIy.png) If I try to plot `Re[F[x,y]]==0` and the result looks like this: ![enter image description here](http://i.stack.imgur.com/WajU3.png) But there is one more solution(branch in the left) that I don't need. How can I separate there solutions?


title: Extension of harmonic number to the real domain

text: What is exactly the domain of validity of the identity:               Sum[1/(k + j - 1), {j, 1, i}] == HarmonicNumber[k - 1 + i] - HarmonicNumber[k - 1]        when `k` is a real number? More generally, could I have a reference about the way `HarmonicNumber[x]` is calculated when `x` is not an `Integer`?


title: Reading Early Version Notebooks

text: I have some very old Mathematica notebooks file (.m) files from Version 2. When I try to open them using Mathematica 8.0 (on a Linux system) Mathematica instantly shuts down (no error message - just closes). However they open and format correctly using WolframCDFPlayer. I can copy from the player but not as cell expressions so a lot of hand editing is required to split and format the cells in the new notebook. Is there any, perhaps undocumented, way to read or import these files into the current version of Mathematica that would retain some degree of the original formatting?


title: Finding corresponding vertex from 3d to 2d

text: I have this simple 3d data points:               v = {{0.`, 0.016821`, -0.5`}, {0.353553`, -0.75`, -0.353553`}, {0.`, -0.75`, -0.5`},         {0.353553`,  -0.013361`, -0.353553`}, {0.5`, -0.75`,         0.`}, {0.5`, -0.020719`, 0.`}, {0.353553`, -0.020719`,          0.353553`}, {0.353553`, -0.75`, 0.353553`}, {0.`, -0.020719`,          0.5`}, {0.`, -0.75`, 0.5`}, {-0.353553`, -0.020719`,          0.353553`}, {-0.353553`, -0.75`, 0.353553`}, {-0.5`, -0.020719`,          0.`}, {-0.5`, -0.75`, 0.`}, {-0.353553`, -0.043838`, -0.353553`}, {-0.353553`,          -0.75`, -0.353553`}};      and                polys = {{2, 3, 4}, {4, 3, 1}, {5, 2, 6}, {2, 4, 6}, {8, 5, 6}, {6, 7, 8},                {10, 8,  7}, {7, 9, 10}, {12, 10, 9}, {9, 11, 12}, {14, 12,                11}, {11, 13, 14}, {1, 3, 15}, {15, 3, 16}, {14, 13, 15}, {16, 14, 15}};      Same data, in 2d representation: following are 2d points                uv = {{0.2505`, 0.500001`}, {0.2505`, 0.624988`}, {0.009907`,           0.500001`}, {0.00005`, 0.624988`}, {0.2505`,           0.375013`}, {0.012311`, 0.375013`}, {0.2505`,           0.250026`}, {0.012311`, 0.250025`}, {0.2505`,          0.125038`}, {0.012311`, 0.125038`}, {0.2505`,          0.00005`}, {0.012311`, 0.00005`}, {0.2505`, 0.874962`}, {0.2505`,          0.99995`}, {0.012312`, 0.99995`}, {0.012312`,          0.874963`}, {0.019862`, 0.749975`}, {0.2505`, 0.749975`}};      and                npolys = {{1, 2, 3}, {3, 2, 4}, {5, 1, 6}, {1, 3, 6}, {7, 5, 6}, {6,                 8, 7}, {9, 7, 8}, {8, 10, 9}, {11, 9, 10}, {10, 12, 11}, {13, 14,                 15}, {15, 16, 13}, {4, 2, 17}, {17, 2, 18}, {13, 16, 17}, {18, 13, 17}};      I am trying to find corresponding vertex order from 3d to 2d. Coordinates are different in both 3d and 2d view. is it possible to do in mathematica?


title: Breaks in plot & blank plots

text: Almost as a follow on from this old question, I am having similar problems again, with slight difference, that if the values are small enough, a completely blank plot is produced.               ξ[z_] := ((z - 1) Gamma[z/2 + 1] Zeta[z])/Sqrt[π^z]          ContourPlot[{Im[ξ[σ + b I]], Re[ξ[σ + b I]]}, {σ, -2, 3}, {b, 100, 120},                 PlotPoints -> 500]      ![enter image description here](http://i.stack.imgur.com/Bnsno.gif) Even with `PlotPoints->500` there are still breaks in the plot. I know I am dealing with very small numbers here, but is there anything I can do to create a clean plot? The plot above is not too bad, but I would really like to look at plots for values of `{b,7000,7010}` - but it just produces a blank plot above `1000`. Is there anything I can to to avoid this? # Update Have tried `Exclusions->None` but creates a plot that is just wrong! ![enter image description here](http://i.stack.imgur.com/QPcuL.gif)


title: How to get rid of all complex numbers and functions?

text: For almost esthetical reasons, I always have been fascinated by infinite sums of series and I always wonder if theyhave a closed form. A couple of days ago, I found on MSE a question related to the convergence of $$S=\Sigma_{n=0}^{\infty}{\frac{n^2 x}{1+n^4 x^2}}$$ where $x$ is a real number. So, I gave the problem to one of my former colleagues who ran Mathematica for this summation. He sent me back the following (surprizing result) $$\frac{\sqrt[4]{-1} \pi \left(\cot \left(\frac{(-1)^{3/4} \pi }{\sqrt{x}}\right)+i \cot \left(\frac{\sqrt[4]{-1} \pi }{\sqrt{x}}\right)\right)}{4 \sqrt{x}}$$ telling that he did not find any way to make it simpler. For sure, the result is a real. I tried to simplify manually, expanding the $cot$ functions and ... arrived nowhere after pages of manual calculations (being almost blind does not make things easier). Could any one tell me what should be the appropriate syntax to be used in order to remove all the complex numbers from this expression ? Any help will be really appreciated.


title: Plot producing many error messages when given complicated function

text: I'm new to _Mathematica_ and am running in to all sorts of silly difficulties with coding in it. I'm trying to calculate a function `f[x, k]`, normalise it with another function `n[k]` and then calculate and plot a thrid function `en[k]` that depends on the first two. Unfortunately, _Mathematica_ won't plot it, and I can't see what I did wrong. I'm sure it's a trivial mistake on my part and I'm sorry to have to ask. Here's my code:               L = 8;     f[x_, k_] :=        Cos[Pi k/(2 L)]^2  Exp[(-(x - k)^2)/2] - Sin[Pi k/(2 L)]^2 (x - L) Exp[(-(x - k)^2)/2];     n[k_] := Integrate[f[u, k]^2, {u, -L, L}];     en[k_] := Integrate[f[v, k] (-f''[v, k] + (v - k)^2  f[v, k]), {v, -L, L}]/n[k];     Plot[en[k], {k, 0, L}]


title: Multiple NIntegrate (again)

text: Basically I have the same question as here: Multiple NIntegrate but since I don't have enough "reputation" I cannot comment there. I want to solve the following multiple Integral numerically at given Points R, m:               Qb[R_, m_] := 3/m^2 + 8/(Sqrt[Pi] m)     NIntegrate[Exp[-c^2] (-4 m^2/(R Sqrt[Pi]) Integrate[     Exp[-x^2] x^2, {x, 0, Infinity}] - 2 m^2/(R Sqrt[Pi])     Integrate[Exp[-x^2] x^2 Integrate[If[R < Sqrt[c^2 + x^2 - 2 c x z],      R/Sqrt[c^2 + x^2 - 2 c x z], 1], {z, -1, 1}], {x, 0, Infinity}])     (3 c^2 - 2 c^4), {c, 0, Infinity}]      But I get error messages: _NIntegrate::inumr: "The integrand (3\ c^2-2\ c^4)\ E^-c^2\ (-44.7156-50.4562\ !(*SubsuperscriptBox[([Integral]), (0), ([Infinity])](*SuperscriptBox[(E), (-Power[ <<2>>])]\\ *SuperscriptBox[(x), (2)]\\ (*SubsuperscriptBox[([Integral]), (-1), (1)]If[Less[<<2>>], Times[<<2>>], 1] [DifferentialD]z) [DifferentialD]x))) has evaluated to non- numerical values for all sampling points in the region with boundaries {{[Infinity],0.}}."_ What is the right way to do this with Mathematica? Edit: To make the problem slightly simpler you can leave out all constants and get rid of the x-integration:               Qb[R_] :=      NIntegrate[     Exp[-c^2] NIntegrate[     If[R < Sqrt[c^2 - 2 c z], R/Sqrt[c^2 - 2 c z], 1], {z, -1, 1}],     {c, 0, Infinity}];     Qb[3.7]      or as an even simpler example               NIntegrate[NIntegrate[y, {x, 0, 1}], {y, 0, 1}]      In **this** case it works to replace the inner NIntegrate by Integrate, but if the inner integral is too complicated for analytic evaluation Mathematica cannot handle it.


title: Integrate equations of motion when force depends on position

text: I'm fairly new to _Mathematica_. I'm trying to test my C++ implementation of a fourth order Runge Kutta method for Newton's equations of motion. I want to test my integrator when the applied force is dependant on the position. I tried to implement Newton's equations of motion in _Mathematica_ as below:               iMass = 4     iVel0 = {1.0, 1.0, 1.0}     iTime = 1.0     iMagn = Dot[iPos, iPos]^0.5     iForce = ((12.3/iMagn) - 1.2)*Normalize[iPos]       (* Applied force is 12.3 / distance from 0 0 1.2 minus 1.2 and pointing towards 0,0,0 *)     iAccel = iForce/iMass     iVel = iVel0 + Integrate[iAccel, time]     iPos = {0.0, 10000, 0.0} + Integrate[iVel, time]}]      _Mathematica_ ran for a couple of hours until I aborted the calculation. How can I get _Mathematica_ to integrate Newton's equations of motion when the applied force is a function of position?


title: Conditional Check on Matrix

text: Suppose I have the following matrix (i,j):               mat = {{19.8134, 54.7015, 64.1866, 75.5597, 88.8358, 83.7313, 93.0299,        88.2537, 101.03, 108.873, 91.8731, 88.097, 82.0075, 88.7164,        83.5672, 69.9254, 56.0149, 31.4328, 19.4179, 6.40299, 1.48507,        0.410448, 0.171642, 0, 0}, {24.2741, 52.6815, 64.4667, 74.8593,        87.6222, 87.1926, 96.3407, 90.0667, 98.2519, 103.496, 89.7926,        85.1259, 83.4889, 88.7111, 86.1852, 75.4296, 53.7778, 34.0667,        19.6889, 7.40741, 2.16296, 0.348148, 0.00740741, 0, 0}, {18.4632,        50.6544, 60.5735, 72.5441, 86.0956, 84.9485, 91.1103, 84.8603,        94.3897, 100.463, 83.6324, 82.9412, 77.4853, 79.6324, 77.9485,        61.9118, 48.7574, 27.8309, 13.8824, 5.96324, 1.60294, 0.529412,        0.0294118, 0, 0}, {19.1212, 59.0985, 71.6818, 86.8182, 96.553,        91.5455, 100.402, 92.6515, 111.068, 111.909, 95.7803, 94.3864,        92.75, 90.8182, 95.3561, 86.197, 73.6136, 51.5682, 40.6742, 15.1515,        3.30303, 0.848485, 0.0757576, 0.030303, 0.030303}, {19.6083,        55.5917, 66.5583, 75.575, 87.6, 89.1417, 96.1083, 92.6917, 108.375,        117.3, 96.7333, 91.8167, 86.6583, 91.7333, 93.45, 79.5333, 60.275,        36.95, 24.3583, 9.60833, 1.76667, 0.416667, 0.00833333, 0.0333333,        0}}      The following is my criteria vector that each element corresponding to each row of the above matrix:               check = {7.94021, 7.95033, 7.44576, 8.83645, 8.38877}      Here is my criteria. If the element in `mat[[i,All]]` is less than the corresponding element in `check[[i]]` vector, I want to replace with the following vector               replacevec = {79.4021, 79.5033, 74.4576, 88.3645, 83.8877}      where each element `(replacevec[[i]])` correspond to each row in `mat` . Could you give me suggestions? Thank you for help.


title: Visualization of matrix transformations

text: I define the "matrix transformation" here as follows: $\left[ \begin{matrix} x_1' \\ x_2' \\ \end{matrix} \right]=\left[ \begin{matrix} a & b \\ c & d \\ \end{matrix} \right]\left[ \begin{matrix} x_1\\ x_2\\ \end{matrix} \right]$, therefore this is a transformation between point and point. it moves $(x_1,x_2)$ to $(x_1',x_2')$ So is there any way to visualize it when you're trying to deform a grid by this?


title: How can I have an axis label automatically positioned below the X-axis?

text: I'm attempting to generate some histograms, and I'd like to automatically label the X-axis. `However, Histogram[. . ., AxesLabel -> {"X", "Y"}]` places the "X" label on the RHS of the axis. How do I direct that the "X" label should be positioned below the axis? I need some automated method (I can of course move it by hand), since I'm going to be generating hundreds of diagrams.


title: webMathematica evaluation gives unexpected results when imported dynamically

text: Let me know if this should be posted on StackOverflow instead - I'm not quite sure where it belongs When calling a page via the JSTL `<c:import>` tag or the JSP Include action, webMathematica gives results that are not consistent with the other components of the page. Consider the following example: page1.jsp:               ...     <c:url value="page2.jsp" var="x">         <c:param name="a" value="4" />     </c:url>     <c:import url="${x}"/>     ...      page2.jsp               1. ${param.a}          2. <%= request.getParameter("a")  %>          3. <msp:evaluate>MSPValueQ[$$a]</msp:evaluate>          4. <msp:evaluate>$ServletRequest@getParameter["a"]</msp:evaluate>          5. <%= request.getAttribute("javax.servlet.include.query_string") %>          6. <msp:evaluate>$ServletRequest@getAttribute["javax.servlet.include.query_string"]</msp:evaluate>      1 and 2 both return the correct value of 4. However, 3 and 4 both evaluate to the empty string. Furthermore, 5 gives the correct string "a=4", but 6 evaluates to the empty string. My best guess is that webMathematica does not update it's parameters when the import is done, so $ServletRequest does not get updated with the new attribute and value of the new GET parameter is not set. What is actually going on here?


title: Why does Dynamic output cause CPU usage when onscreen?

text: I write such a line in _Mathematica_ :               {Slider[Dynamic[s]], Dynamic[f[x_] := s*x]}      After evaluation, the CPU immediately runs at full power. And if you scroll the page, it turns out that as soon as this line appear on the screen, the CPU begin to work. This really confused me a lot. Can anyone help?


title: How can I highlight the points lying between two lines in a ListPlot?

text: I have a list of numbers like the following:               list = Table[RandomInteger[1000], {i, 1000}];      And I plot them so:               ListPlot[list]      ![enter image description here](http://i.stack.imgur.com/1Q9Wd.png) I have drawn the black lines on the plot myself. I'd like to have `min` and `max` variables as a function of `y`, which once set, produce these lines in the chart and highlight the data between the lines. How can I do this?


title: TreeForm expression that will automatically spread nodes vertically so labels do not overlap

text: My deeply and unevenly nested lists and equations generate a TreeForm image which is too small and compressed to use. Then we must expand it manually by grabbing the edge of the image, and sometimes this requires irritating time and effort, and huge expansions. Will some clever person please show me how to force the size of the TreeForm image to be large enough that no cells in the image overlap vertically? So no level will vertically overlap any other level? Then, in some instances, but not as important, a second option to force the image also to be large enough so no two cells on the same level overlap horizontally? (This latter must be an option only, not the default, because the span may be extremely large horizontally for large databases. Also, it might be best that partial overlaps be permitted.) I imagine running TreeForm with these options, and then being able to use the vertical and horizontal scroll bars to see any part of the nested structure. This would solve a lot of the problems being addressed by other solutions and questions about TreeForm.


title: How can I save a Manipulate's control settings to a dataset?

text: This is probably an extremely simple question. I have a manipulate that sets variables used to define an offset, amplitude, frequency and phase of a trigonometric function.               Manipulate[       Module[{Vac,Vdc, ω, ϕ, f},         Vac = ctrlVac;                      (* AC Voltage *)         Vdc = ctrlVdc;                      (* DC Offset *)         f = ctrlf;                          (* Frequency *)         ω = 2 π f;         ϕ = ctrlPhi;                        (* Phase Offset *)         gFunc = ctrlgFunc;                  (* Function *)         Plot[ Vdc + Vac  gFunc[ ω t + ϕ],{t,0, 0.4}]],       {{ctrlgFunc,Sin,""},{Sin,Cos, Tan, Cot }},Delimiter,       {{ctrlVac,1.5,Subscript["V","ac"]}, -10,10},       {{ctrlVdc, 0.5, Subscript["V","dc"]}, -1,1},Delimiter,       {{ctrlf, 10, "Frequency"}, 0.001,100},       {{ctrlPhi, 0, "ϕ"}, 0, 2 π},       ControlPlacement->Left, Paneled->True]      I would like to use the `Manipulate` as an editor that sets the values of the variables in the code snippet above and then passes them on as parameters to a function along with other sets of variables. Is there a way to add a button to save the current values to a dataset?


title: Draw plot with locator & slider

text: I would like to create a plot whereby both the slider and the locator 'draw' the plot. In the following code, the locator & the slider act independently:               f[x_] := Sin[x];     Manipulate[With[{x0 = Clip[p[[1]], {0, 20}]}, Plot[f[x], {x, 0, t},      ImagePadding -> 20, PlotRange -> {{0, 20}, {-2, 2}}, LabelStyle -> (FontFamily ->      "Ariel"), Epilog -> {PointSize[Large], Red, Tooltip[Point[#], #] &@{x0, f[x0]}}]],      {t, 0.001, 20}, {{p, {0, 0}}, Locator, Appearance -> None}, AppearanceElements -> None]      I would like to get both to work together, so the slider 'draws' the plot, as does the locator when it is dragged. Here is an illustration of what I am trying to achieve: ![enter image description here](http://i.stack.imgur.com/eRRQn.gif)


title: Why does repeating an equation help in FindRoot?

text: I'm trying to understand this behavior of `FindRoot`. Consider a sample function (the one I'm actually interested in is far more complicated, but has similar issues) and the following arguments:               crazyFunction[x_, y_] := N@Norm[{x + 2 y}]     yact = RandomReal[{-10, 10}, 2]~Join~{RandomReal[{100, 250}]};     gv = yact + RandomReal[{-.1, .1}, 2]~Join~{RandomReal[{-5, 5}]};     sampledata = crazyFunction[#, {a, b, c}] == crazyFunction[#, yact] & /@      {{1, 2, 3}, {2, 3, 4}, {4, 5, 6}};      Basically, I'm applying the sample function for a particular `yact` value, at three `x` values, and setting it equal to the function evaluated with three "unknown" `y` values `{a,b,c}`. To solve for the "unknown" values, I used `FindRoot` with initial guessed value `gv` randomly perturbed from the actual values:               sol = FindRoot[sampledata, Transpose@{{a, b, c}, gv}, MaxIterations -> 1000]      Note, this likely will throw a warning `(* FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal ... *)`. To evaluate the quality of the solution, I compare the `Norm` of the difference between the actual `yact` and the solved `y` (normalized to the `Norm` of `yact`):               Norm[yact - {a, b, c} /. sol]/Norm[yact]     (* Out[]:= 0.0540657 *)      which isn't a terrible value. My thinking here is, I have three unknowns -- `a`, `b`, and `c` -- and three different equations for the different `x` values, so that should be enough to solve the problem. In fact, without three equations `FindRoot` won't work. I.e.:               FindRoot[sampledata[[1]], Transpose@{{a, b, c}, gv}, MaxIterations -> 1000]     (* FindRoot::nveq: The number of equations does not match the number of variables in... *)      But, if instead of using three, different equations, I simply repeat the same equation three times:               sampledata = Table[crazyFunction[#, {a, b, c}] == crazyFunction[#, yact] &@{1, 2,3}, {3}];     sol = FindRoot[sampledata, Transpose@{{a, b, c}, gv}, MaxIterations -> 1000];      Not only does it not give the `lstol` warning, but it actually gets a more accurate result! Consider:               dat=Table[yact=RandomReal[{-10,10},2]~Join~{RandomReal[{100,250}]};      gv=yact+RandomReal[{-.1,.1},2]~Join~{RandomReal[{-5,5}]};      sampledata=crazyFunction[#,{a,b,c}]==crazyFunction[#, yact]&/@{{1,2,3},{2,3,4},{4,5,6}};      sol=Quiet@FindRoot[sampledata,Transpose@{{a,b,c},gv},MaxIterations->1000];      Norm[yact-{a,b,c}/.sol]/Norm[yact],{1000}];          datSamedata=Table[      yact=RandomReal[{-10,10},2]~Join~{RandomReal[{100,250}]};      gv=yact+RandomReal[{-.1,.1},2]~Join~{RandomReal[{-5,5}]};      sampledata=Table[crazyFunction[#,{a,b,c}]==crazyFunction[#, yact]&@{1,2,3},{3}];      sol=Quiet@FindRoot[sampledata,Transpose@{{a,b,c},gv},MaxIterations->1000];      Norm[yact-{a,b,c}/.sol]/Norm[yact],{1000}];          Histogram[{dat, datSamedata}, "Log"]      ![Mathematica graphics](http://i.stack.imgur.com/4cnFL.png) Note the log-binning. Using the same equation three times is far more accurate than using three different equations! So, my question is: **Why is repeating the same equation three times far more accurate than using three different equations?**


title: How to get all leaves from a graph's specific node

text: Let's say I have this graph (The code to generate the graph is at the end) ![sample graph](http://i.stack.imgur.com/B0JH4.png) How can I extract all the leaves comming from, let's say "cluster3"?, i.e. {100, 92, 87, 89} ![sample graph](http://i.stack.imgur.com/ON89L.png) I guess I have to first extract the subgraph with "cluster3" as root vertex ![sample graph](http://i.stack.imgur.com/oyNJ0.png) and then filter the result. This last part should be easy. What I'm finding hard to get is extracting the subgraph. I tried using the Subgraph functions doing like: Subgraph[myGraph, UndirectedEdge[_, cluster3]] But I don't get what I want ![sample graph 2](http://i.stack.imgur.com/mhwlW.png) Probably this is trivial and I'm just not seeing it. Any kind of help would be super useful. Thanx! This is what I used to create the graph               Needs["HierarchicalClustering`"];          MakeClusteredTree[data_,leaves_,opts:OptionsPattern[]]:=Module[{clusters,expr,ett,edges,optsGraph=FilterRules[opts,Options[Graph]],optsAgglomerate=FilterRules[opts,Options[Agglomerate]]},clusters=Agglomerate[data->leaves,optsAgglomerate];expr=(i=1;Replace[clusters,Cluster[a_,b_,___]:>Symbol["cluster"<>ToString[i++]][a,b],{0,Infinity}]);ett=SparseArray`ExpressionToTree[expr];edges=UndirectedEdge@@@(ett[[All,All,1]]);Graph[(UndirectedEdge@@@edges),GraphLayout->{"LayeredEmbedding","RootVertex"->(UndirectedEdge@@@edges)[[1,1]]},VertexLabels->"Name",optsGraph,ImagePadding-> Full]]          data = {100, 43, 87, 1, 49, 32, 79, 42, 89, 92};          MakeClusteredTree[data, ToString /@ data, {Linkage -> "Average"}]      ====Final Notes==== The MakeClusteredTree function is completely based on this post (highest of high fives to kguler). I just changed it a little bit for my original purpose and another little bit for this post (I'm using more complicated data, huge trees and originally, I only visibly label the leaves. I changed the VertexLabels for this example so I can show you the names of all nodes.


title: How to use filling in ContourPlot

text: I want to fill region between different contours, e.g. `ContourPlot[{c1 = f1, c2 = f2}, ...]` a la the filling options for `Plot` like `Filling -> {1->{2}}`. Is it an easier way than superimposing two contour plots then manually excluding regions?


title: How do I transform a rasterized graphic's coordinates back to its original ListPlot data coordinates?

text: From this question I successfully made an elliptical fit for my data. However, when I try and collect the datapoints within the ellipse via this question the coordinates of my ellipse correspond to an ellipse of a rasterized image of my listplot data and not the original. How can I transform or scale the ellipse that fits the rasterized image to the original listplot. Ok, with all that said heres an example.               data = RandomReal[NormalDistribution[], {100000, 2}]     p = ListPlot[data, ImageSize -> 4000];     f = FillingTransform@ColorNegate@Binarize@p // DeleteSmallComponents     {c, s, t} = 1 /. ComponentMeasurements[f, {"Centroid", "SemiAxes", "Orientation"}]     Show[Rasterize[p], Graphics[{Red, Rotate[Circle[c, s],t]}]]      where I get a nice image: ![example data](http://i45.tinypic.com/34tej38.jpg) however, the coordinates c, s, t of the ellipse are pixle coordiantes corresponding to the rasterized image rather than data coordinates. So when I need the ellipses parameter to do any calculations I get bunk results. The image processing approach would be the best as I am filtering out the most dense cluster of data. Thanks so much.


title: How to import a text file into Classify?

text: I have a text file like as follows.               {     "XXX" -> "A",      "YYY" -> "A",     "ZZZ" -> "B"     }       I'd like to import this so I can send it directly to `Classify[]`. I've tried importing as `CSV` and `Text` but neither work. Example (That doesn't work):               data = Import["sample.txt", "CSV"];     c = Classify[data];      Although I'd settle for a normal CSV if that isn't possible.


title: Mathematica cannot find the c compiler

text: I installed Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1 Then, I installed Mathematica 10 trial version. I did:               Needs["CCompilerDriver`"]          $CCompiler = {"Compiler" -> GenericCCompiler,      "CompilerInstallation" ->      "C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\bin",      "CompilerName" -> "cl.exe"};          Compile[{{x}}, x^2 + Sin[x^2], CompilationTarget -> "C"];      I got:               CreateLibrary::badcomp: Compiler specification "Compiler" -> GenericCCompiler does not specify a compiler driver listed by CCompilers[Full]. >>          Compile::nogen: A library could not be generated from the compiled function. >>      How can I set up c compiler which I installed for Mathematica?


title: Why does the name of a pattern affect the result of a transformation rule?

text: I was playing a little dirty, trying to get a template for defining a `Curl[]` operator. I wrote the following rule, which I knew was going to spit out a few errors, because all symbols there (including the lists), were undefined:               Cross[{d[1], d[2], d[3]}, {2, 3, 4}] /. Times[a_, b_] -> b[[a]]      Notwithstanding the errors, the result I got was what I wanted:               (* {d[2][[4]] + d[3][[-3]], d[1][[-4]] + d[3][[2]], d[1][[3]] + d[2][[-2]]} *)      with a few more replacements, you can almost see the `Curl[]` operator materializing. Sadly, I forgot that the symbol `a` was already in use in may main `.nb`, so I changed it to `c`. Look:               Cross[{d[1], d[2], d[3]}, {2, 3, 4}] /. Times[c_, b_] -> b[[c]]      But now the results are completely different!               (* {(-3)[[d[3]]] + 4[[d[2]]], (-4)[[d[1]]] + 2[[d[3]]], (-2)[[d[2]]] + 3[[d[1]]]} *)      Wow! I `Traced` the evaluation, and could easily find out where the both processes started to differ, but I couldn't understand why. Any ideas?


title: Efficiently importing XPM matrix data into Mathematica

text: The XPM file format is an image file format. Although it is primarily intended for icon pixmaps, it can also be used to store matrix data. For example, the GROMACS chemical simulation package uses it in the program g_hbond to export hydrogen bond existence matrices. A sample XPM file, generated by **g_hbond** is below:               /* XPM */     /* Generated by g_hbond_d */     /* This file can be converted to EPS by the GROMACS program xpm2ps */     /* title:   "Hydrogen Bond Existence Map" */     /* legend:  "Hydrogen Bonds" */     /* x-label: "Time (ps)" */     /* y-label: "Hydrogen Bond Index" */     /* type:    "Discrete" */     static char *gromacs_xpm[] = {     "201 2   2 1",     "   c #FFFFFF " /* "None" */,     "o  c #FF0000 " /* "Present" */,     /* x-axis:  0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 */     /* x-axis:  8 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 10 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 11 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 12 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 13 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 15 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 */     /* x-axis:  16 16.1 16.2 16.3 16.4 16.5 16.6 16.7 16.8 16.9 17 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 18 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 19 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 20 0 */     /* y-axis:  0 1 0 */     "ooooooooooooooo oooooooooooooooooooo oo oooo ooooooooooo  oooooooooooooooooooooooooooooooooo   o oooooooooooooooo ooo oooooooooooooooooooooooooooooooooooooo ooooo ooo  oooooo  o oooooooo   ooooo oooooo",     "                                                                                o o                       "      This file is also available here, on Google Docs. The last two lines provide the matrix data. If there is an `"o"` character, then that particular hydrogen bond (each line represents a different hydrogen bond) exists at that time. Do you know if there are any functions or add-on packages for Mathematica that can read in XPM files? In particular, I would like to read in the last two lines:               "ooooooooooooooo oooooooooooooooooooo oo oooo ooooooooooo  oooooooooooooooooooooooooooooooooo   o oooooooooooooooo ooo oooooooooooooooooooooooooooooooooooooo ooooo ooo  oooooo  o oooooooo   ooooo oooooo",     "                                                                                o o                       "      and store the result as a `List`, `Array`, or `SparseArray`. Probably `SparseArray` would be desirable because the values in the matrix are binary -- a particular hydrogen bond either exists at a certain time or it doesn't. Also, it doesn't really matter what character we use to represent existence (in the above, they use `"o"`) and absence (in the above, they use `" "`). Do you have any advice on the best way to read in this data? The sample above is only very small; however, the files can get _much_ larger, so I probably will not be able to import the entire file at once using `Import`. Probably I will have to read the file piecewise, perhaps using `Stream`. Thanks for your time.


title: How to check if a database connection is open?

text: In[32]:= SQLConnections[]          Out[32]= {SQLConnection["db", 1, "Closed", "<>"],       SQLConnection["db", 2, "Closed", "<>"],       SQLConnection["db", 3, "Open", "Catalog" -> "db",        "ReadOnly" -> True]}          In[33]:= Cases[SQLConnections[], SQLConnection[__, "Open", __]]          Out[33]= {}      doesn't work. Why it doesn't match the one open connection expression?


title: How to properly handle mutual imports of multiple packages?

text: I'm new to the mathematica platform and I am developing a simulation framework as my first exercise and have been tearing my hair figuring how to make packages interact with each other. Ill explain a minimum package experiment I developed to understand my problems and please I would like a theoretical explanation of why this happens, if it is a bug or if I am just dumb with mathematica. The thing is that if I have packages that use each others exported symbols or functions inside their functions, after the first package is loaded he loads the others declared as needed as well, but then only that package that was loaded first can reference all other exported stuff, and the others for some reason can only look at the exported data of later packages/contexts in the context path. To make every package able to see every other exports I need to load them again individually. This makes no sense to me, I thought the whole point of having needs in any package constructor is to avoid loading myself every package of my packages set. Is this a bug? Btw, the exported symbols from different packages are found right away by mathematica is just the symbols inside functions that cant reference each other. So basically I defined three packages, ja1,ja2,ja3. All have the same structure like this: **Package ja1**               BeginPackage["SimulationsSystem`ja1`", { "SimulationsSystem`ja2`", "SimulationsSystem`ja3`"}]          shadow::usage="shadow"     var1::usage = "var1"     pro1::usage = "pro1"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=1;     var1=1;     pro1[]:=var1+var2+var3          End[] (* End Private Context *)          EndPackage[]      **Package ja2**               BeginPackage["SimulationsSystem`ja2`", { "SimulationsSystem`ja1`", "SimulationsSystem`ja3`"}]          shadow::usage="shadow"     var2::usage = "var2"     pro2::usage = "pro2"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=2;     var2=1;     pro2[]:=var1+var2+var3     End[] (* End Private Context *)          EndPackage[]      **Package ja3**               BeginPackage["SimulationsSystem`ja3`", { "SimulationsSystem`ja1`", "SimulationsSystem`ja2`"}]          shadow::usage="shadow"     var3::usage = "var3"     pro3::usage = "pro3"     (* Exported symbols added here with SymbolName::usage *)            Begin["`Private`"] (* Begin Private Context *)           shadow=3;     var3=1;     pro3[]:=var1+var2+var3     End[] (* End Private Context *)          EndPackage[]      **Commands run** : so after defining the packages I tried to run each pro function, called each var and called shadow to see the nearest Package/context working. And here is the result:               In[2]:= << SimulationsSystem`ja2`     $ContextPath          Out[5]= {"SimulationsSystem`ja2`", "SimulationsSystem`ja1`", \     "SimulationsSystem`ja3`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[6]:= pro1[]          Out[6]= 2 + SimulationsSystem`ja1`Private`var2          In[7]:= pro2[]          Out[7]= 3          In[8]:= pro3[]          Out[8]= 1 + SimulationsSystem`ja3`Private`var1 + \     SimulationsSystem`ja3`Private`var2          In[9]:= var1          Out[9]= 1          In[10]:= var2          Out[10]= 1          In[11]:= var3          Out[11]= 1          In[12]:= shadow          Out[12]= 2          In[13]:= << SimulationsSystem`ja3`     $ContextPath          Out[14]= {"SimulationsSystem`ja3`", "SimulationsSystem`ja2`", \     "SimulationsSystem`ja1`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[15]:= pro1[]          Out[15]= 2 + SimulationsSystem`ja1`Private`var2          In[16]:= pro2[]          Out[16]= 3          In[17]:= pro3[]          Out[17]= 3          In[18]:= var1          Out[18]= 1          In[19]:= var2          Out[19]= 1          In[20]:= var3          Out[20]= 1          In[21]:= shadow          Out[21]= 3          In[22]:= << SimulationsSystem`ja1`     $ContextPath          Out[23]= {"SimulationsSystem`ja1`", "SimulationsSystem`ja3`", \     "SimulationsSystem`ja2`", "SimulationsSystem`SimulationsSystem`", \     "SimulationsSystem`Models`Basic`", \     "SimulationsSystem`SimulFunctions`", \     "SimulationsSystem`TurnPackages`", \     "SimulationsSystem`EventFunctions`", "SimulationsSystem`Classes`", \     "PacletManager`", "WebServices`", "System`", "Global`"}          In[24]:= pro1[]          Out[24]= 3          In[25]:= pro2[]          Out[25]= 3          In[26]:= pro3[]          Out[26]= 3          In[27]:= var1          Out[27]= 1          In[28]:= var2          Out[28]= 1          In[29]:= var3          Out[29]= 1          In[30]:= shadow          Out[30]= 1      You can see in the output that only after packages are loaded by themselves they are able to recognize every other packages' exported symbols and functions.


title: Efficient way of finding shortest distance between two sets of points in mathematica

text: I have two sets of 3D points, say               a = RandomReal[1, {10, 3}];     b = RandomReal[1, {10, 3}];      I wanna find the first N pairs that have shortest distance between the two sets, my current approach is to form a `NearestFunction` from the first list and map it to the second(say, N=3):               f = Nearest[a];     c = Flatten[f/@b, 1];      Then get the result:               N=3;     Transpose[{c[[#]], b[[#]]}]&@ Ordering[Norm/@(c-b),N]          Output={{1st pair},{2nd pair},{3rd pair}}      **Question:What is the more efficient way of finding shortest distance pairs of two sets in mathematica?** -edit- In my actual case, I want to determine the intersection of two shapes(manifolds), but the analytic form of these shapes are not available. I can only compute points on these shapes through numerical process(`NDSolve`). So I want to use enough many points to approximate these shapes, and use `Intersection`-like operation to find points that lay approximately on both shapes. The number of points is very large(eg. 10^7), and the points may in high dimensional space(eg. 4D). Excuse me for my crippled English. I am greatly appreciate any suggestions, thank you very much!


title: Zooming the interval arround $0.333\cdots $, whats wrong?

text: I'm trying to zoom the interval arround $0.333\cdots$ with:               Manipulate[      ListLinePlot[Table[{n, Sum[3/10^x, {x, n}]}, {n, 1, 20, 1}],        Mesh -> All,        PlotRange -> {{0, 20}, {(Sum[3/10^t, {t, g}] - 1/10^g), (Sum[3/10^t, {t, g}] + 1/            10^g)}}], {g, 2, 20, 0.001}]      I know that I can use the interval `(Sum[3/10^t, {t, g}] - 1/10^g), (Sum[3/10^t, {t, g}] + 1/10^g)` because I've evaluated this:               Table[N[Sum[3/10^t, {t, n}] - 1/10^n, n], {n, 2, 10}]      Which yields:               (* {0.32, 0.332, 0.3332, 0.33332, 0.333332, 0.3333332, 0.33333332, 0.333333332, 0.3333333332} *)      And:               Table[N[Sum[3/10^t, {t, n}] + 1/10^n, n], {n, 2, 10}]      which yields:               (* {0.34, 0.334, 0.3334, 0.33334, 0.333334, 0.3333334, 0.33333334, 0.333333334, 0.3333333334} *)      But something weird is happening and the plot is jumping in a weird way. I have no clue of what's going on.


title: Is there a way to get user input when running a script on a Linux terminal?

text: I have access to a node of a Linux cluster, on which Mathematica is installed. However, I do not have access to a Linux GUI. Typically I write and test Mathematica scripts on my Windows personal computer (with the typical GUI/front end). Then, I run the scripts on the Linux terminal because the terminal is significantly faster than my desktop computer (my scripts read and write a _lot_ of data). I use the command:               math < test.txt      where `test.txt` is a text file containing Mathematica code. I have been using this command successfully to run my scripts. I just always need to make sure that I do not try to print graphics to the screen, since I don't have a Linux GUI. However, now I would like to write a script that prompts the user for input. For example, this code works fine on the Windows GUI: Print["start"]; str = InputString[]; Print["string: " <> str]; Print["finish"]; But, it fails on the Linux terminal, generating this console output: > Mathematica 7.0 for Linux x86 (64-bit) Copyright 1988-2008 Wolfram Research, > Inc. > > In[1]:= start > > In[2]:= ? > > In[3]:= finish > > In[4]:= Is there any way I can prompt the user for input on a Linux terminal? The input does not necessarily need to be interactive. For example, I can imagine there being a way to pass an input string to `math` by a command like:               math -input "This is my input string." < test.txt      but I am not sure what is the syntax to do this. **Addendum:** `InputString[]` works on the terminal if I simply **enter** a terminal using the command:               math      and then type `InputString[]` in the input prompt. However, this is _not_ how I want to run my scripts, since this (I think) would require me to retype **every** command, line by line.


title: How do I use the ShowLegends function to produce a legend for my framed graphic?

text: I'm new to this site and new to Mathematica as you can see from my question. I'm also new to programming, btw. I'm trying to produce a legend for my plot which I've coded as follows:               Needs["PlotLegends`"]     ds1 = {{0, 0.53}, {10, 1.00}, {20, 2.19}, {35, 3.61}};     ds2 = {{0, 0.52}, {10, 0.91}, {20, 1.97}, {35, 3.09}};     ds3 = {{0, ds1[[1, 2]] - ds2[[1, 2]]},             {10, ds1[[2, 2]] - ds2[[2, 2]]},             {20, ds1[[3, 2]] - ds2[[3, 2]]},             {35, ds1[[4, 2]] - ds2[[4, 2]]}           };     mf1 = LinearModelFit[ds1, x, x];     mf2 = LinearModelFit[ds2, x, x];     mf3 = LinearModelFit[ds3, x, x];     m1 = mf1["BestFit"]; m2 = mf2["BestFit"]; m3 = mf3["BestFit"];          Show[       {         ListPlot[{ds1, ds2, ds3},             PlotMarkers -> Automatic, PlotStyle -> {Blue, Red, Orange}         ],          Plot[{m1, m2, m3}, {x, 0, 35}, PlotStyle -> {Blue, Red, Orange}]       },        Frame -> True,        FrameLabel -> {"Time (min)","Inorganic Phosphate Concentration (mM)"},       ImageSize -> {400, 300}     ]      So, I'd like to use the `ShowLegend` function to have the legend displayed outside of the frame. I know that I can use the `LegendPosition` function to do this. My problem, however, is the tags. How do I get the legend to show the names of the plots (ds1, ds2, ds3, m1, m2, and m3)?


title: Manually launching remote kernel results local process frozen

text: I'm trying to launch a Linux (Ubuntu latest) machine as a slave of my local PC (Windows 8). Both machine have Mathematica 9 installed. However, I'm behind a router, so I think it's a little more complicated. I found out that mathematica uses port ranging from 58000 to 59000 (at least at the moment I ran it, because actually it just asks the system for one, which increases constantly), so I forwarded the router's port 58000~59000 to my PC. Following this FAQ, I went ahead and set up my local kernel, and start to listen. The prompted window said > Link created on: 58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx so I went ahead, opened up putty, connected to the remote machine, started mathematica kernel using `math`, and ran               $ParentLink = LinkConnect["58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx", LinkProtocol->"TCPIP"]      Immediately, on my local machine, a message box pops up that says:               Out[1]= LinkObject[58917@104.xx.xxx.xxx,58918@104.xx.xxx.xxx, 60, 1]      which I suppose means that the connection is successful. However, on my local PC, the entire mathematica process freezes and becomes "not responding". ![screenshot](http://i.stack.imgur.com/XGYEN.png) Has anyone ever encountered the same problem? Why is that? * * * **Update** : After a long _long_ time, the message box finally printed something new: ![enter image description here](http://i.stack.imgur.com/tKFNs.png) Not a good news huh? Again what might be happending?


title: lists of conditions

text: I have got coordinates in two list of Latitude and Longitude and would like to check if those coordinates are in a certain grid Example lists are:               qLon={-7.48333, -10.4667, -8.66667, -7.48333}     qLat={53.5, 52.5, 53.1167, 51.9833, 51.0167}      Grid borders:                 SLat=47       NLat=55       ELon=-15       SLon=-5      My idea was:               If[ELon <= # <= WLon, "","Outside Grid"] & /@ qLon     If[SLat <= # <= NLat, "","Outside Grid"] & /@ qLat      I would like to merge them, to do the test in one go, like:               If[ELon <= #1 <= WLon && SLat <= #2 <= NLat,...      but could not get it working. Another thing is the output; it should only show something if there is a point outside the grid.


title: How can I open an Excel file and modify it in Mathematica?

text: I wanted to ask how can I view an Excel file from a _Mathematica_ notebook and modify it. I have seen a similar question, Open Excel file with Mathematica, but the answer involves .NET. Is there any other way to open an Excel file and modify it?


title: Find all roots of an interpolating function (solution to a differential equation)

text: I'm trying to find all the roots of the solution to a differential equation. Using NSolve or Reduce I don't get the roots, so I'm using an iterative method which I found in physicsforums.com. This method solves my problem, but you have to choose the increment and thus in some cases it might give headaches. I wonder if there is any more general approach. Following is a sample code:               data = NDSolve[{1.09 x''[t] - 0.05 x'[t] + 1.1759 Sin[x[t]] == 0,              x[0] == Pi/3, x'[0] == 0}, x, {t, 0, 50}]       > {{x->InterpolatingFunction[{{0.,50.}},<>]}} First attempt with no success:               sol = NSolve[x'[t] == 0 /. data , t]       > NSolve::ifun: Inverse functions are being used by NSolve, so some solutions > may not be found; use Reduce for complete solution information. >> > > {{t->InverseFunction[InterpolatingFunction[{{0.,50.}},<>],1,1][0.]}} Second attempt with no success:               sol = Reduce[x'[t] == 0 /. data , t]       > Reduce::inex: Reduce was unable to solve the system with inexact > coefficients or the system obtained by direct rationalization of inexact > numbers present in the system. Since many of the methods used by Reduce > require exact input, providing Reduce with an exact version of the system > may help. >> > > Reduce[{InterpolatingFunction[{{0.,50.}},<>][t]==0},t] Third attempt, works fine, but manually choosing `dt` could cause problems with some equations:               dt = 0.1;      tmin = 0.;      tmax = 50.;           Union[Table[t /. FindRoot[x'[t] == 0 /. data ,{t, tInit, tmin, tmax}],         {tInit, tmin + dt,tmax - dt, dt}], SameTest->(Abs[#1 - #2] < 10^-2&)]       > {0., 3.26812, 6.58301, 9.95657, 13.4054, 16.9538, 20.6403, 24.533, 28.7857, > 34.2571} Is there any more elegant method to find all roots in a range?


title: How can I randomize the elements of a list?

text: Is there a straightforward way to go from an ordered list like:               ord = {a, b, c, d, e, f, g, h}      to a disordered list like:               randompos = {c, h, d, g, a, b, f, e}      I can use something like:               DeleteDuplicates @ RandomChoice[ord, 50]      but it's not really robust. Is there an easier way?


title: Assigning a particular value to array elements

text: I have an array of 10000 elements. I want to randomly assign energy to these 10000 elements using Gaussian or Exponential distribution, such that each time a particular element is selected its energy should also be shown in the output. Can anyone suggest me how to solve this problem? Let's say, I have 10 elements in the array {8,4,6,2,9,0,5,1,7,3} and I am assigning energy to these 10 elements randomly. After that I am selecting one of the element in the array, say 7, when I select this number I also want to know the energy that number possesses. This is the program I wrote to generate 1000 elements.               l = 0;     For[i = 0, i < 10, i++,      For[j = 0, j < 10, j++,       For[k = 0, k < 10, k++,        Xarray[l] = A[i, j, k];        Print[Xarray[l]];        l++;        ]       ]      ]     Xarray[5]      When `Xarray[5]` is given it will show the coordinate it possesses. In addition to this I want to know the energy when I am giving `Xarray[5]`, `Xarray[998]`, etc.


title: How to get rid of nested matrices

text: If I type into Mathematica               TensorProduct[IdentityMatrix[2],IdentityMatrix[2]]      It gives me a result that has nested matrices. How do I turn that into a normal matrix without any nesting? Thanks


title: Controlling CDF window size

text: I want to ask how can I control the `CDF` `WindowSize` in such a way that the end user can minimise its size upto some extent only. For example, If the `WindowSize` is less than or equal to {300,200}, then it should not be minimised but, it can be maximised.               Dynamic[(width = CurrentValue["WindowSize"][[1]];             height = CurrentValue["WindowSize"][[2]];      If[width <= 300, (width = 301), (width = CurrentValue["WindowSize"][[1]])];      If[height <= 200, (height = 201), (height = CurrentValue["WindowSize"][[2]])];      Panel[Button["Click1"], {width, height}, ImageSize -> {width, height}])]


title: Problem with using the results of ParametricNDSolve in a ParametricPlot3D

text: I new to _Mathematica_ and I have a problem with certain equations. I want to plot a trajectory in spherical coordinates given by the equations:               (1 + α^2)*(Abs[γ])^-1*θ'[t] == (Sin[2*θ[t]]*Subscript[H, d]*α)/                2 + ((Cos^2)[ϕ[t]]*Sin[2*θ[t]]*α - Sin[2*ϕ[t]]*Sin[θ[t]])*Subscript[H, k]/                2 - (α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) +            M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j]      and               (1 + α^2)*(Abs[γ])^-1*ϕ'[t] == -Cos[θ[t]]*Subscript[H, d]*α - (2*(Cos^2)[ϕ[t]]*Cos[θ[t]] -                  α*Sin[2*ϕ[t]])*Subscript[H, k]/2 - Cos[θ[t]]*(α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] -              Sin[β]*Sin[θ[t]]) -              M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j]      My (crude) code is:               sol = ParametricNDSolve[{(1 + α^2)*(Abs[γ])^-1*θ'[t] == (Sin[2*θ[t]]*Subscript[H, d]*α)/            2 + ((Cos^2)[ϕ[t]]*Sin[2*θ[t]]*α - Sin[2*ϕ[t]]*Sin[θ[t]])*Subscript[H, k]/            2 - (α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) +             M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j], (1 + α^2)*(Abs[γ])^-1*ϕ'[t] ==                  -Cos[θ[t]]*Subscript[H, d]*α - (2*(Cos^2)[ϕ[t]]*Cos[θ[t]] - α*                  Sin[2*ϕ[t]])*Subscript[H, k]/2 -             Cos[θ[t]]*(α*M*(Cos[β]*Cos[θ[t]]*Cos[ϕ[t]] - Sin[β]*Sin[θ[t]]) -             M*Cos[β]*Sin[ϕ[t]])*Subscript[α, j], ϕ[0] == 0, θ[0] == 0},            {ϕ[t], θ[t]}, {t, 0, 100},            {α, Subscript[H, d], Subscript[α, j], Subscript[H, k], M, γ, β}]      and I try to plot it:               ParametricPlot3D[      Evaluate[{M*Cos[ϕ[t]]*Sin[θ[t]] /. sol,          M*Sin[ϕ[t]]*Sin[θ[t]] /. sol,          M*Cos[θ[t]] /. sol} /. {α -> 1,          Subscript[H, d] -> 1, Subscript[α, j] -> 1,          Subscript[H, k] -> 1, M -> 1, γ -> .1, β -> .1}, {t,         0, 100}]]      but the plot isn't displayed and I don't get any errors. Does anyone know what am I doing wrong? Thanks in advance!


title: Vertices, their labels, and how to refer to them?

text: In the examples I have seen, graph vertices in Mathematica are usually explicit small integers. However, Wolfram documentation says that vertices can be any arbitrary expression (eg., george, x^2, London, 5). Nevertheless, it seems that vertices are always _referred to_ by number, that is, by the position of the vertex expression in `VertexList[gr]`. This can be confusing. For example, if I build a graph like this, using nonconsecutive vertex numbers,               Graph[1<->2, 2<->10, 10<->3, 3<->4]      then I still have to refer to the vertices as if I had made each vertex number equal to its creation order, as if I had built the graph with strictly consecutive vertex numbers:               Graph[1<->2, 2<-3 ,3<->4, 4<->1]       Am I understanding this correctly?


title: Splitting a string into substrings of length 1 and 2

text: There is already a thread on how to split a string into equal sized chunks. I'm wanting to split a string into sets of substrings of length 1 and 2. For example, if I have the string "123456", my list would include elements such as {12,3,4,56}, {1,2,3,45,6}, and {1,2,34,56}. I found this little bit of Python code, but 1) I don't know how to translate it into Mathematica code and 2) it gives you strings with a bunch of extra commas (because it's basically just distributing n commas through the string in different ways). I suspect there is a very simple way of doing this in Mathematica.


title: How to plot small values

text: I wonder, why small values (eg. 10^-1600) would not show on a plot? Here is a small example, where Evaluate gives a list of very small values and Plot does not show them, starting from x=20.               testfunc[x_] := 10^(-16 x)      testvalues = {x -> {10, 20, 30, 40, 50, 60, 70, 80, 100}};     Evaluate[testfunc[x]] /. testvalues     LogPlot[Evaluate[testfunc[x]], {x, 1, 100}, AxesOrigin -> {0, 10^-1600}]      ![enter image description here](http://i.stack.imgur.com/D9jkY.jpg) I guess it has something to do with precision, but I could not find any solution for Plot function yet and would appreciate any help. Had no luck with SetPrecision/WorkingPrecision.


title: ShearingTransform and Dynamic

text: Background: I have a geometric transformation composed of a `RotationTransform`, `ScalingTransform` and `ShearingTransform`, I can use dynamic constructs with rotations and scalings but this does not (seem to) work with the `ShearingTransform`. Consider the following snippet:                 DynamicModule[{shr, deg = 30},        shr0 = ShearingTransform[deg Degree, {1, 0}, {0, 1}];        shr1 = Dynamic[ShearingTransform[deg Degree, {1, 0}, {0, 1}]];        shr2 = ShearingTransform[Dynamic[deg Degree], {1, 0}, {0, 1}];       Column[{          Slider[Dynamic[deg], {0, 90, 1}],          GeometricTransformation[{Blue,            Rectangle[{0, 0}, {3, 1}]},           shr0] // Graphics}        ]]      Note that the snippet does not work (as expected) : moving the slider does not change the angle of the shear. See `shr1` and `shr2` for alternatives I have already tried. **Question: How can I make the angle in a`ShearingTransform` dynamic, such that it works in the context of the snippet above?**


title: Calculate deviation of sum of several equal normal distribution

text: I have a normal distribution with mean m and standard deviation d. How can I calculate what will be the deviation if I add N such distributions? As I understand, mean will be m*N. Will standard deviation be d*N? P.S. It looks like I should be using standard variances vs standard deviation. Sum of Gauss(Mean1, Standard Variance1) + Gauss(Mean2, Standard Variance2) = Gauss (Mean1 + Mean2, Standard Variance1 + Standard Variance 2). This way standard variance for N will be v*N, which mean that d=sqrt(N)*d


title: ParallelTable: explicitly assign iterator values to kernels

text: I've a construct that reads               ParallelTable[      MyFunction[i],      {i, 16}     ]      Now, MyFunction[i] takes an amount of time to be evaluated which is a decreasing function of i. When I evaluate with multiple kernels however, mathematica assigns close values of i to the same kernels. In this example it has assigned i=1,2 to kernel 8 and i=3,4 to kernel 7, and this is of course not optimized at all. Out of 8 cores I get a speedup of only 2.49 which is quite unsatisfactory, due to the fact that a huge part of the work was made by 2 kernels leaving the other 6 with a relatively low load. ![Parallel Kernel Status screenshot at the end of the evaluation](http://i.stack.imgur.com/W99Vv.png) Is there a way to explicitly assign values of i to the kernels?


title: How can I replace bi-directional DirectedEdge pairs in a Graph with a single UndirectedEdge?

text: The Cayley graphs produced by Mathematica 8.0's `CayleyGraph` function represent actions that are their own inverses in an unconventional way: rather than using a single edge without arrows, it uses two edges, each represented by an arrow. Is there a way to replace all (and only) pairs of such reflexive arrows in a Cayley diagram with a single undirected edge, while leaving any unpaired directed edges untouched? For example is there a way to make edges in this               CayleyGraph[DihedralGroup[4]]      ![enter image description here](http://i.stack.imgur.com/Flv2n.png) look like this ![enter image description here](http://i.stack.imgur.com/WCzz6.png) * * * Note that I'm aware that one could generate the desired output "manually", using `Graph` (as was done to generate the example above), but the solution I'm seeking must work for _far_ more complex graphs than the one illustrated here from the simple group specifications that can be provided to `CayleyGraph`.


title: Why can't Mathematica "Solve" my equation?

text: I am trying to get Mathematica to solve the following equality in terms of $w_i$ $\displaystyle \frac{\sum_{i = 1}^{n} x_i }{\sum_{i = 1}^{n} y_i} = \frac{\sum_{i = 1}^{n} ( (\frac{x_i}{y_i}) w_i ) }{n} $ (Background: http://math.stackexchange.com/questions/137332/relationship- between-ratios-and-averages-of-ratios) But it's telling me "This system cannot be solved with the methods available to Solve." Now, I'm guessing this is because I haven't given Mathematica enough information about my assumptions (specifically, that $w_i$ is expressible as a function of $x_i$ and $y_i$, or something similar) What am I doing wrong here, and how would I go about using Mathematica to solve equalities like these?               Solve[Sum[Subscript[x, i],           {i, 1, n}]/         Sum[Subscript[y, i],           {i, 1, n}] ==         Sum[(Subscript[x, i]/            Subscript[y, i])*           Subscript[w, i],           {i, 1, n}]/n,        Subscript[w, i]]      PS.) I realize my title stinks... I blame myself for not even knowing enough about what my problem is to give this question a cogent title. If someone could Edit the question and give it a real title and/or suggest one, I'd be appreciative.


title: How to find the position of elements in a list satisfying criteria

text: Say I have a list `x={2,4,6,8,10}` and I want to find out the positions of the elements that are greater than 7. `Select[x, #>7&]` gives the elements themselves, and `Position[x,8]` gives the position of the elements satisfying one of the possible criteria, but what I am looking for would be a mix of the two returning `{4,5}`. Any suggestions?


title: How to avoid spaces between numbers when displaying TagBox(es)

text: The instruction : `DisplayForm[RowBox[List[0,1,Superscript[2,3],Superscript[1,2],a]]]` displays a gap between the first two items of the list ![enter image description here](http://i.stack.imgur.com/YKZkx.png) but if one is careful not to have two consecutive integers, there is no gap `DisplayForm[RowBox[List[0,a,1,Superscript[2,3],Superscript[1,2],a]]]` ![enter image description here](http://i.stack.imgur.com/DQA6S.png) I would like to know if there is a way to disable (locally) the space inserted by Mathematica between two integers in this case to have something like that: ![enter image description here](http://i.stack.imgur.com/VLFny.png) I would like the result to stay a TagBox or InterpretationBox, easy to copy/paste, if possible.


title: Transparent textures don't show

text: > **EDIT** For now, I'm going to accept Brett's answer. It's a way to get > transparency back by having 3D calculations done in software instead of > hardware. It addresses the symptoms but not the causes. As I wrote above, my > PC and graphics card are provably able to do it, but there's something in > the interaction with MMA that disables it after restarts. Anyone who solves > this gets the Accept check. * * * > **Edit** I got conformations from several users with the following hardware: > >   * Simon Woods: Windows 7 64 bit, with an NVidia GTX 550 Ti graphics card. >   * texasAUtiger: Windows 7, 64 bit on Intel on Intel iCore i7-2760QM 2.4 > ghz, NVidia NVS 4200M graphics card > * * * I have this problem where several of the examples in the doc page of `Texture` don't work.               data = Table[{1, 0, 0, a}, {u, 0, 1, 1/100}, {a, 0, 1, 1/100}];          vtc = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};     coords = {{{0, 0, 0}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}}, {{0, 0,           0}, {1, 0, 0}, {1, 0, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1,           1, 1}, {1, 0, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {1, 1,           1}}, {{0, 1, 0}, {0, 0, 0}, {0, 0, 1}, {0, 1, 1}}, {{0, 0,           1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}}};          Graphics3D[{Texture[data],        Polygon[coords, VertexTextureCoordinates -> Table[vtc, {6}]]},       Lighting -> "Neutral", Boxed -> False]      is supposed to give: ![Mathematica graphics](http://i.stack.imgur.com/yz9oS.png) but I get this: ![Mathematica graphics](http://i.stack.imgur.com/0Auig.png)               data1 = Table[{1, 2/3, 0, If[u^2 + v^2 < 1/2, 0, 1]}, {u, -1, 1,          1/100}, {v, -1, 1, 1/100}];     data2 = Table[{0, 0, 1, If[u^2 + v^2 < 1/2, 0, 1]}, {u, -1, 1,          1/100}, {v, -1, 1, 1/100}];      Additionally,               Graphics3D[{FaceForm[Texture[data1], Texture[data2]],        Polygon[coords, VertexTextureCoordinates -> Table[vtc, {6}]]},       Lighting -> "Neutral", Boxed -> False]      should yield: ![Mathematica graphics](http://i.stack.imgur.com/55K26.png) but I get the empty cube again. Then there's the example in the `Scope>Texture styling` section of the doc page which is supposed to result in: ![enter image description here](http://i.stack.imgur.com/V73Wc.gif) In my case I get: ![Mathematica graphics](http://i.stack.imgur.com/2F8j2.png). This is not a general transparency issue as               Plot3D[x^4 + y^4 - 5 x^2*y^2, {x, -3, 3}, {y, -3, 3},       PlotStyle -> Opacity[0.8], Mesh -> None]      gives me this: ![Mathematica graphics](http://i.stack.imgur.com/lK9So.png) I'm using a 1 year old Dell XPS-15 (model L501 X)Running Windows 7-64 with an nVidia GeForce GT 435M graphics card, driver version 8.17.12.6639. I reported this earlier on Mathgroup and got the advice to update my drivers which I did and it sure helped. However this is not the end of the story as the behavior returned soon afterwards. I have updated the driver various times using both nVidia's and Dell's newest version and it always was a short-lived solution. Last time I tested it, I installed the _same_ version of the driver over the existing one and the transparent textures showed up as intended in my notebook even without re- executing the code, only to disappear after MMA's next restart. So, apparently my system is able to handle transparent textures but there is some interaction between MMA and the driver that causes this ability to be switched off. **Update** This issue seems to have been resolved in Mathematica 9. All of the above mentioned problems did not reappear when I tested them in the trial version of V9.


title: Copy last/second last (etc.) input from history into current cell

text: I like to use terminals (e.g. `gnome-terminal`) where you can use the up key to copy the last command into the current input 'field'. For example, to repeat the last command you just have to press `up`, `enter`. Or, to modify the last input and re-run, it is just `up`, modify, `enter`. As beginner I often make mistakes, or experiment by slightly changing previous inputs. Is there any way in which I can obtain this convenient input behavior in the _Mathematica_ front end?


title: Difference In Eigenvectors

text: When running my program in both Mathematica and MathCad, I end up with the same eigenvalues, but different eigenvectors. The ones in MathCad are normalized, which the documentation for Mathematica says they too are normalized. I also tried `Normalize[]` and they still differed. Any advice for how to change it so that they match up? EDIT:: Code               {{0. + 0. I, -0.00105652 + 0.00306633 I, -0.000992072 - 0.000550179 I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I, -0.00080248 - 0.000276499 I,        3.94975*10^-6 - 7.12212*10^-6 I,        0.0000192495 + 6.63251*10^-6 I, -7.8995*10^-6 +         0.0000142442 I, -2.53122*10^-6 - 2.0506*10^-6 I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I}, {0.00119848 - 0.00323969 I,        0. + 0. I, -0.00089753 + 0.00242618 I, -0.000743608 - 0.000434551 I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, -1.5511*10^-6 + 8.53409*10^-6 I, -0.000868186 -         0.000321173 I, 8.75277*10^-6 - 0.0000149778 I,        0.0000203377 + 7.52365*10^-6 I, -8.75277*10^-6 +         0.0000149778 I, -2.64607*10^-6 - 2.24413*10^-6 I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I}, {-0.00124465 - 0.00025056 I, 0.000991057 - 0.00253121 I,        0. + 0. I, -0.000658751 + 0.00168248 I, -0.000461387 -         0.000281434 I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I,        0.0000212182 + 8.30765*10^-6 I, -3.59755*10^-6 +         0.0000178707 I, -0.000909167 - 0.00035597 I,        9.49275*10^-6 - 0.0000155626 I,        0.0000212182 + 8.30765*10^-6 I, -9.49275*10^-6 +         0.0000155626 I, -2.73555*10^-6 - 2.41019*10^-6 I, 0. + 0. I,        0. + 0. I, 0. + 0. I,        0. + 0. I}, {0. + 0. I, -0.000915438 - 0.000197309 I,        0.000705296 - 0.00173145 I,        0. + 0. I, -0.00034951 + 0.000858025 I, -0.000154043 -         0.0000968679 I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 3.97422*10^-6 - 0.0000184388 I,        0.0000218358 + 8.89464*10^-6 I, -3.97422*10^-6 +         0.0000184388 I, -0.000935629 - 0.000381122 I,        0.000010041 - 0.0000159676 I,        0.0000218358 + 8.89464*10^-6 I, -0.000010041 +         0.0000159676 I, -2.79628*10^-6 - 2.53224*10^-6 I, 0. + 0. I,        0. + 0. I, 0. + 0. I}, {0. + 0. I,        0. + 0. I, -0.000555325 - 0.000123831 I,        0.000361803 - 0.000870433 I, 0. + 0. I,        6.4961*10^-6 - 0.0000156284 I, 0.000167434 + 0.000106958 I,        0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, -3.83436*10^-6 - 1.7215*10^-7 I,        4.17683*10^-6 - 0.0000187311 I,        0.0000221515 + 9.20749*10^-6 I, -4.17683*10^-6 +         0.0000187311 I, -0.000949159 - 0.000394527 I,        0.0000103313 - 0.0000161729 I,        0.0000221515 + 9.20749*10^-6 I, -0.0000103313 +         0.0000161729 I, -2.82664*10^-6 - 2.59656*10^-6 I, 0. + 0. I,        0. + 0. I}, {0. + 0. I, 0. + 0. I,        0. + 0. I, -0.000180652 - 0.0000402588 I, -6.49204*10^-6 +         0.0000156244 I, 0. + 0. I, 0.000374561 - 0.000901456 I,        0.00049078 + 0.000313423 I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, -3.83319*10^-6 - 1.71599*10^-7 I,        4.17309*10^-6 - 0.0000187258 I,        0.0000221458 + 9.20173*10^-6 I, -4.17309*10^-6 +         0.0000187258 I, -0.000948914 - 0.00039428 I,        0.000010326 - 0.0000161692 I,        0.0000221458 + 9.20173*10^-6 I, -0.000010326 +         0.0000161692 I, -2.82609*10^-6 - 2.59538*10^-6 I,        0. + 0. I}, {0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0.000190732 + 0.0000410344 I, -0.000361392 + 0.000888151 I,        0. + 0. I, 0.000716521 - 0.00176091 I, 0.00080346 + 0.000504823 I,        0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, -3.76634*10^-6 - 1.40845*10^-7 I,        3.96361*10^-6 - 0.0000184233 I,        0.0000218189 + 8.87822*10^-6 I, -3.96361*10^-6 +         0.0000184233 I, -0.000934908 - 0.000380418 I,        0.0000100257 - 0.0000159566 I,        0.0000218189 + 8.87822*10^-6 I, -0.0000100257 +         0.0000159566 I, -2.79465*10^-6 - 2.52885*10^-6 I}, {0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0.000541679 + 0.000108715 I, -0.00066847 + 0.00171026 I, 0. + 0. I,        0.000999783 - 0.00255791 I, 0.00109362 + 0.000666203 I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, -3.63939*10^-6 - 8.56735*10^-8 I,        3.58173*10^-6 - 0.0000178461 I,        0.0000211913 + 8.28283*10^-6 I, -3.58173*10^-6 +         0.0000178461 I, -0.000908015 - 0.000354907 I,        9.46946*10^-6 - 0.0000155449 I,        0.0000211913 + 8.28283*10^-6 I, -9.46946*10^-6 +         0.0000155449 I}, {0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I,        0.000857822 + 0.000155255 I, -0.000904508 + 0.00245062 I, 0. + 0. I,        0.00120425 - 0.00326273 I, 0.00135116 + 0.000788249 I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, -3.46257*10^-6 - 1.56372*10^-8 I,        3.08334*10^-6 - 0.0000170362 I,        0.0000203025 + 7.49351*10^-6 I, -3.08334*10^-6 +         0.0000170362 I, -0.000869931 - 0.000321086 I,        8.72413*10^-6 - 0.0000149543 I,        0.0000203025 + 7.49351*10^-6 I}, {0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0.00112915 + 0.000178104 I, -0.00106069 + 0.00308684 I, 0. + 0. I,        0.0013247 - 0.00385516 I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I, -3.24913*10^-6 + 5.87823*10^-8 I,        2.53158*10^-6 - 0.0000160499 I,        0.0000192081 + 6.60019*10^-6 I, -2.53158*10^-6 +         0.0000160499 I, -0.000819963 - 0.000281752 I,        3.93415*10^-6 - 7.10805*10^-6 I}, {0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0.00135075 + 0.000179137 I, -0.00114114 + 0.00360727 I, 0. + 0. I,        0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I, 0. + 0. I,        0. + 0. I, -3.01338*10^-6 + 1.28696*10^-7 I,        1.98264*10^-6 - 0.0000149497 I,        0.0000179729 + 5.68564*10^-6 I, -9.91319*10^-7 +         7.47487*10^-6 I, -0.000749264 - 0.000237026 I}, {1, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,        0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,        0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,        0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}      I will work on getting the MathCad, but the first few values of the 19th eigenvector should be -.001048-.001033i, -.002461-.00404i...


title: What BarChart Option controls Joined line thickness?

text: Is there a named option that controls the thickness of the line segments that appear in `BarChart` with options `ChartLayout -> "Stacked"`, `Joined->True`? It is not `EdgeForm`, since `ChartBaseStyle -> EdgeForm[None]` is the value set in the following example: ![enter image description here](http://i.stack.imgur.com/IgZwH.png) It's unclear what `Directive` can be passed. Changing `Thickness` value in `ChartBaseStyle -> {Thickness[0.0001], EdgeForm[None]}` has no effect for example.


title: Skipping over iterator values in a Table

text: I have been using the built-in function `Table` for some computations. (The following is not an actual representation of the equations I am using). $$\text{Table}[f[k]=g[k],\{k,1,10\}]$$ However, the assignment $f[k]=g[k]$ is not true for one $k$ value, say $k=6$. That is, say, $g[k]=k^2+1$ for $k\neq 6$ and $g[6]=1$ (when $k=6$). I can then break the table into two parts: $\{k,1,5\}$ and $\{k,7,10\}$. Is there any other (more efficient) way of doing this?


title: Testing the convergence when solving an integral equation

text: I am trying to find the solution of an integral equation such that a certain convergence criterion is fulfilled. Now the problem is that the function doesn't look like what I am actually expecting, in the sense that I have solved the equation also with a normal iteration, and there I get the "expected" (physical) result, but there I don't know how to implement the convergence criterion, at least not in an elegant way. The other problem I have is that the integration actually goes from 0 to 1, but since _Mathematica_ spits errors when I use 1 as the upper limit of integration, I have to replace 1 with 0.999.... Is there a better way to do this? Here the code               α = 2.85;     g = (Pi/2) α;     Nf := 2;          cs[x_] := 2 ArcCos[x]/Sqrt[1 - x^2];     csh[x_] := 2 ArcCosh[x]/Sqrt[x^2 - 1];     prefB[p_, k_, d_] :=      (p^2 + k^2 (1 - 1/d^2))/Sqrt[p^2 d^4 - 1/4 ((p^2 + k^2) d^2/k - k )^2];     pieceB[k_, d_] :=        If[d B[k]/k^2 < 1, cs[d B[k]/k^2], If[d B[k]/k^2 > 1, csh[d B[k]/k^2], 2]];          B[p_] = p^2 ;     iterstep :=      (values =      Parallelize[     Table[{p, p^2 +  g/(Pi^3  Nf) (NIntegrate[             prefB[p, k, d] ((d^2 B[k]^2/k^4 - 1) (Pi - g pieceB[k, d]) +                 B[k ]/k^2 d  g^2 csh[g])/(d^2 B[k]^2/k^4 + g^2 - 1),             {d, 0, 1/(1 + p)}, {k, p d/(d + 1), p d/(1 - d)},             WorkingPrecision -> 16,             PrecisionGoal -> 2,             MaxRecursion -> 100,            AccuracyGoal -> 16,             Method -> {"SymbolicPreprocessing", "OscillatorySelection" -> False}] +            NIntegrate[            prefB[p, k, d] ((d^2 B[k]^2/k^4 - 1) (Pi - g pieceB[k, d]) +                 B[k ]/k^2 d  g^2 csh[g])/(d^2 B[k]^2/k^4 + g^2 -1),             {d, 1/(1 - p), Infinity},             {k, p d/(d + 1), p d/(d - 1)},              WorkingPrecision -> 16, PrecisionGoal -> 2,             MaxRecursion -> 100, AccuracyGoal -> 16,            Method -> {"SymbolicPreprocessing","OscillatorySelection" -> False}])},             {p, 0, 0.99999, 1/20}]];          B[p_] = Interpolation[values , p, InterpolationOrder -> 4,   Method -> "Hermite"])               Do[iterstep, {3}] // AbsoluteTiming      The last code works relatively ok (although it gets extremely slow), but the problem is that I have no good control over convergence. Is there a way to tell the Do loop to stop when a certain convergence criterion is reached? Also, the problem with the upper integration limit still remains...


title: Combining graphics

text: # Original question I would like to put a coloured grid behind the following plot: ![enter image description here](http://i.stack.imgur.com/VdZAQ.gif) which was generated by:               a = Table[x, {x, 1, 10}];     b = Table[10 x, {x, 1, 10}];     ListLinePlot[{Table[x^2, {x, 1, 10}]}, InterpolationOrder -> 0,     PlotRange -> {{0, 10}, {0, 100}}, GridLines -> {a, b}, GridLinesStyle ->        Directive[GrayLevel[0.8], Dashed], AspectRatio -> 1]      so that I could shade certain squares of the grid so it looks something like: ![enter image description here](http://i.stack.imgur.com/QDrgu.png) for example. # Update1 Using Kuba's code below, it is fairly straightforward to overlay an x^2 shaded plot with an x^3 ListLinePlot using the following code:               data = Table[{x, x^2}, {x, 0, 10}];     ceiling = {#, Ceiling[#2 + 1, 10]} & @@@ data;     floor = {#, Floor[#2, 10]} & @@@ data;     a = Table[x, {x, 1, 10}];     b = Table[10 x, {x, 1, 10}];     c = ListLinePlot[{Table[x^3, {x, 1, 10}]}, InterpolationOrder -> 0,      PlotRange -> {{0, 10}, {0, 100}}, GridLines -> {a, b},      GridLinesStyle -> Directive[GrayLevel[0.8], Dashed],      AspectRatio -> 1, PlotStyle -> {Thick}];     Show[ListPlot[{data, ceiling, floor}, InterpolationOrder -> 0,      Joined -> True, AspectRatio -> 1, Filling -> (2 -> {3}),      GridLines -> {Range[10], Range[0, 100, 10]},      GridLinesStyle -> Directive[GrayLevel[0.8], Dashed],      PlotStyle -> {None, None, None}], c]      which generates: ![enter image description here](http://i.stack.imgur.com/Eyq4T.gif) without too much fiddling. Is there a similarly straightforward way of showing a shaded x^3 plot & ListLinePlot x^2 without running into problems with the dimensions of the grid (without fiddling around with the dimensions each time)? # Update2 Thanks to Kuba's code: ![enter image description here](http://i.stack.imgur.com/4UP8e.gif) with:               lineData[f_, max_, min_: 0] := Table[{x, f[x]}, {x, min, max}];     shadeData[f_, max_, min_: 0] :=      Transpose[{{#, Ceiling[#2 + 1, 10]}, {#, Floor[#2, 10]}} & @@@      Table[{x, f[x]}, {x, min, max}]]          With[{stdOpt = {InterpolationOrder -> 0,      GridLines -> {Range[10], Range[0, 300, 10]},      GridLinesStyle -> Directive[GrayLevel[0.8], Dashed],      Joined -> True, AspectRatio -> 1}},      ListPlot[{lineData[#^2 &, 10], ##} & @@ shadeData[#^3 &, 10],      Filling -> (2 -> {3}), PlotStyle -> {Thick, None, None}, stdOpt,      PlotRange -> {{0, 10}, {0, 100}},          Epilog -> {Red, Opacity[0.5], Rectangle[{1, 10}, {2, 20}], Blue,      Opacity[0.5], Rectangle[{2, 40}, {3, 50}]}          ]]      # Update3 Having some fun with it: ![enter image description here](http://i.stack.imgur.com/CmM4i.gif) with:               shadeData[f_, max_, min_: 0] :=      Transpose@Table[{{x, Ceiling[f[x] + If[FractionalPart[f[x]] == 0.5, 0.5, 0], 1]},     {x, Floor[f[x], 1]}}, {x, min, max}]          Animate[Quiet[With[{stdOpt = {InterpolationOrder -> 0, GridLines -> {Range[-10, 28,     1], Range[-10, 14]}, GridLinesStyle -> Directive[GrayLevel[0.8], Dashed],      Joined -> True, AspectRatio -> 0.25}}, ListPlot[shadeData[(Sin[# + n])*10 &, 28],      Filling -> (2 -> {1}), FillingStyle -> Directive[Opacity[0.5], Orange],      PlotStyle -> {None, None, None}, stdOpt, Axes -> False, Frame -> False,      ImageSize -> 600, PlotRange -> {{0, 24}, {-10, 10}}]]], {n, 0, 2 \[Pi]},      AnimationDirection -> Forward, AnimationRate -> 0.5]      and ![enter image description here](http://i.stack.imgur.com/Gyd6Y.gif) ...etc :)


title: Transfer of symbols between contexts

text: As many others (I guess) I'm struggling with the handling of contexts within Mathematica. I'm working on a new package definition with the usual syntaxt specified by the Mathematica documentation:               BeginPackage["example`"];          <Entry Points>          Begin["`Private`"]          <Definitions>          End[];          EndPackage[];      Now I want to use symbols generated in another Notebook and saved with DumpSave for efficiency. The code in this other Notebook is thus               DumpSave[<some mx file>,{symbol1,symbol2,...,symboln}]      when I import these symbols into my package it looks like this:               BeginPackage["example`"];          <Entry Points>          Begin["`Private`"]          DumpGet[<some mx file>];     <Definitions>          End[];          EndPackage[];      there is already the catch: The Symbols are not automatically loaded into the private context of the package (which is example`Private` in the above code snippet) but into the original context of the Notebook where the mx file has been generated (which is Global` in my case)! Thus I need to convert the symbols either into the private context in the package definition (which would the following statements               example`Private`symbol1=Global`symbol1;     example`Private`symbol2=Global`symbol2;     .     .     .     example`Private`symboln=Global`symboln;     Remove[Global`symbol1,Global`symbol2,...,Global`symboln])      or save the symbols already into the right context by using               example`Private`symbol1=symbol1;     example`Private`symbol2=symbol2;     .     .     .     example`Private`symboln=symboln;     DumpSave[<some mx file>,{example`Private`symbol1, example`Private`symbol2,        ..., example`Private`symboln}]      in the generating Notebook (which would be my preferred solution). I need to do all of this clumsy setup because I do not want to have the symbols in the Global` context because then the symbols are visible outside of the package, which is not necessary and may cause shadowing problems too. Now my question: Is there a quick way to copy symbols over from one context into another? Something like               Set[Evaluate[example`Private`#],Global`#]&/@{symbol1,symbol2,...,symboln}      would be preferrable. However above statement does not work... Any ideas?