title: Return a string from a vector containing a string and a number

text: I currently have a List of the form,               {{String_1, 8.}, {String_2, `101.}, {String_3, 37.}, ..., {String_n, 28.}}      Along with another list,               {{8, 37, ... }, ..., {..., 28, 101}}      And I would like to return,               {{String_1, String_3, ...}, ..., {..., String_n, String_2}}      In short, I would like to replace the lists of numbers in the second list with their corresponding strings (given in the first list). I imagine this has quite a simple solution, but searching through Mathematica's documentation hasn't been very fruitful. Any help is appreciated.


title: Rewrite an expression as a sum of $SU(2)$ characters?

text: I have an expression of the form $$q^{-3/2} t^{-7/2}[4qt^2(t + q t^2) + t^2 (q + t) (1 + q t (1 + q t))],$$ I can factor it and write it as $4((qt)^{1/2} + (qt)^{-1/2}) + (qt+1 + (qt)^{-1})((\frac{q}{t})^{1/2} + (\frac{q}{t})^{-1/2}),$ and conclude that it has content $4(1/2,0)\oplus(1,1/2),$ in terms of $SU(2)$ representations. Assuming $f(t,q)$ has the form in which such a rewriting is possible, I want it to express it in the form $\sum_{j_L, j_R}N^{(j_L, j_R)}((qt)^{j_L}+ (qt)^{j_L - 1} + \dots (qt)^{-j_L})((q/t)^{j_R} + \dots + (q/t)^{-j_R}),$ where $(j_L, j_R)$ are half integers or integers. For those of you familiar with representation theory, I want to express this as a sum of characters of representations of $SU(2)$. The rewriting is simple enough to do by hand for easy expressions like above, but I want to do it for longer ones. How can I do it using _Mathematica_?


title: What options control PairedHistogram axes style?

text: What options control axes style in PairedHistogram? Here's the online doc. I'm trying to control axes color, thickness, and probably font size on the tick marks. but the options are confusing me:               data = Transpose@        Table[{RandomInteger[{1, 10}], RandomInteger[{1, 10}]}, {100}];     PairedHistogram[data[[1]], data[[2]],      PlotRange -> {All, All}, BarOrigin -> "XAxis",       ChartBaseStyle -> {EdgeForm[None]},       ChartStyle -> {{Blue, Orange}, None,         None},(*ChartElementFunction-> \     ChartElementDataFunction["SegmentScaleRectangle","Segments"-> \     5,"ColorScheme"->"SolarColors"],*)      ChartLegends -> {"A", "B"},       ImageSize -> 300, AspectRatio -> 1]      ![enter image description here](http://i.stack.imgur.com/XSACL.png)


title: How to fix the "Module" function, for implicit funcitons?

text: I wanted to make a function which gives the frequencies of a number in a specific list, when I came accros this problem. This is what I tried:               row = {-1, 1, 2, 3, -1, 1, 2, -1, 1, -1, -2, -3,        1, -1, -2, -3, -4, -5, 1, 2};          frequencyRow =       Round[HistogramList[row, {Min[row] - 1, Max[row] + 1, 1}]];          lengthRow = Map[f, Part[frequencyRow, 1]]          (*{f[-6], f[-5], f[-4], f[-3], f[-2], f[-1], f[0], f[1], f[2], f[3],           f[4]}*)          frequency = Append[Part[frequencyRow, 2], 0]          (*{0, 1, 1, 2, 2, 5, 0, 5, 3, 1, 0}*)          mode[n_] := Module[{f}, {lengthRow = frequency}; f[n]]          mode[2]          >f$821[2]      (So the implicit fucntions do not give the outcome I want. However;)               mode2[n_] :=       Module[{f}, {{f[-6], f[-5], f[-4], f[-3], f[-2], f[-1], f[0], f[1],           f[2], f[3], f[4]} = {0, 1, 1, 2, 2, 5, 0, 5, 3, 1, 0}}; f[n]]          mode2[2]          (*3*)      (If you use the exact outcome of the functions, the Module function does give the right outcome)               goal = Map[mode2, row]          (*{5, 5, 3, 1, 5, 5, 3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 1, 1, 5, 3}*)      If you know how to fix this to make it work for the implicit functions as well, so I can chance the imput without changing the formula all the time, that would be nice. Or if you see a way to do this proces faster or easier, that would even be better.


title: Integrating over data points from an external source (wolfram|alpha and weather)

text: I moved to another city and the weather sucks. Sometimes I feel like getting sad and so I go to _wolfram|alpha_ and check for example ${}$ ![enter image description here](http://i.imgur.com/nYzrp.png) http://www.wolframalpha.com/input/?i=weather+in+Rome+vs.+London ${}$ Today I feel like getting depressed. Consequently I wonder if there is a way to import all the data into _Mathematica_ and write a function               TemperatureComparison[{city1,city2},{date1,date2}]      which should evaluate to $$ \frac{ \int_{\text{date 1}}^{\text{date 2}} \left(T_{\text{city 2}}(t)-T_{\text{city 1}}(t)\right) \text dt } { t_{\text{date 2}}-t_{\text{date 1}} },$$ $T_{\text{city X}}(t)$ being the temperature in $\text{city X}$ at time $t$.


title: What's the difference between Inactive and HoldForm?

text: In version 10, Mathematica not only added `Inactive` / `Activate` but also highlighted this change in the "New in 10" page (in Core Language Enhancements). Thus, I suppose it should be something useful. However, I didn't understand in which sense it is better than the good old `Hold` (`HoldForm`) / `ReleaseHold` mechanism. I noticed a few differences, but all of those are minor: (1) `Inactive` objects are printed in a lighter color. `HoldForm` objects are printed in normal color. (2) There is an `IgnoringInactive` function to include inactive objects into pattern matching. It would be nice to hear if there are more important differences.


title: 'not a valid variable' error when trying to solve 13 equations with 13 variables

text: I want to solve 13 variables by 13 equations. And here is my program:               Solve[{RD == (1.1*NR)^0.6, 0.6*1.1^0.6*NR^-0.4 == wr/em, wr == em^0.2,       Q == (0.6 NQ^(-1/3) + 0.02 R^(-1/3) + 0.38 K^(-1/3))^-3,        0.6 (Q/NR)^(4/3) == w, 0.02 (Q/R)^(4/3) == em,        0.38 (Q/K)^(4/3) == 0.04, NR + NQ + NU == 1 - L,        w (NR + NU) == wr*NR, C1/C2 == 4*em,        L == (1/1.04*0.2^0.2*0.8^0.8*em^-0.2*w)^-0.2,        Q == C1 + 0.25 Q*em^0.5,        0.25*Q*em^0.5 - em*C2 - em (R - RD) == 0}, {RD, NR, wr, em, Q, NQ,        R, K, w, NU, L, C1, C2}]      After executing this I get the following message > >     :General::ivar: 1.11396/(w/<<2>>^<<4>>)^0.2 is not a valid variable. >> >   Here is how it looks in my notebook. Could anybody kindly answer what's going on?


title: How can I save and recall my own function?

text: In MATLAB, I can save and recall my own function using an M-File(function or script)   How can I do something similar in _Mathematica_? I already searched and know how to define functions and modules like the following:               f[x_]:=Sin[x]+Cos[x]       g[x_]:=Module[{a}, a*f[x]]      When I restart _Mathematica_ , however, my own function is deleted. Of course, I can save my notebook(.nb) file, but it is just saving my script, not saving my definition of the function. How can I deal with this problem?


title: Factorize Parametric Polynomials

text: Is there a possibility to factorize a parametric polynomial expression - meaning that the coefficients are defined as parameters, and not as specific numbers? My example - a polynomial in `s`, with `R1, ..., R5` and `C1, ..., C2` being parameters:               LP2nTfDen = R1 R4 + R4 R5 + C2 R1 R2 R4 s + C1 R1 R3 R5 s + C2 R2 R4 R5 s -                 C1 C2 R1 R2 R4 R5 s^2      I'd like _Mathematica_ to transform the expression in the form `(A + s) (B + s)` ..., `A`, `B`, etc. being expressions of `R1, ..., R5`, `C1`, `C2`. Is this possible?


title: Interpolation of a table with 4 parameters

text: I have a huge data file which I need to do some analysis on it. The file is built in this way that for each 4 variables, there is a value of the function:               List={{x,y,z,w},f[x,y,z,w]}      A part of the real data is the following `List`:               tab={{{0.0001, 1., -1., 1.*10^-6}, 0.6704}, {{0.0001, 1., -0.85,3.98107*10^-6}, 0.964659}, {{0.0001, 1., -0.7,0.0000199526}, 0.491676}, {{0.0001, 1., -0.55, 0.0001}, 0.0974736}};      For each value of the `x` and `y` parameters, I need to `NIntegrate` with respect to `z` and `w`. If I could have the whole function wrt all parameters, `f[x,y,z,t]`, I would do:               tab2=Flatten[Table[{{x,y},NIntegrate[f[x,y,z,w], {z,zmin,zmax},{w,wmin,wmax}]},{x,xmin,xmax},{y,ymin,ymax}],1];      and then I would `Interpolate` `tab2` with respect to `{x,y}`:               final=Interpolation[tab2];      I have almost 4 million points, I can do the analysis in this way, but how can I be sure that the `Interpolation` function is a correct function, while there are too many approximations to make it? I know that `Interpolation` works for any n-dimension, but it won't be acurate anymore for more than 2 parameters. Is there a way that I do this kind of analysis without needning to `Interpolate` with respect to all parameters? For example is there a way that I can just `Interpolate` with respect to `{z,w}`, I do the `Integration`, then I `Interpolate` the result with respect to `{x,y}`?


title: Randomly packing spheres of fixed radius within a cube

text: How can I have _Mathematica_ randomly place spheres in a cube so they won't overlap? The cube is $20 \times 20 \times 20$, and the spheres have a radius of $0.7$.


title: Adjust spacing between a section title and the first contained cell

text: In my day-to-day work with Mathematica I use a stylesheet I have derived from Mathematica's default stylesheet. One modification I would like to make to my stylesheet is to reduce the spacing between a section title and the first cell inside the section. This is _not_ controlled by the CellMargins option. Is there another notebook option that can be set to reduce this gap?


title: Set some Method options for NDSolve globally while allowing others to change

text: In a code base that is difficult to change for unrelated issues, I have many invocations of `NDSolve` that look like the following:               NDSolve[equations, variables, {t, 0, 100},       Method -> {"ExplicitRungeKutta", "StiffnessTest" -> False}]      This has stopped working with _Mathematica_ 9.0, because something is timing out (our problem appears similar to the one described here). The fix is to change the invocation to look like this:               NDSolve[eqns, vars, {t, 0, 100},       Method ->         {"ExplicitRungeKutta",          "StiffnessTest" -> False,          "EquationSimplification"->"Solve"}]      I would like to be able to change the part of the `Method` option involving `"EquationsSimplification"` to `"Solve"` globally, in such a way that it won't be clobbered when a call leaves that option alone, but sets other options (like using the `"ExplicitRungeKutta"` method, or turning off `"StiffnessTest"`). This will allow me to fix things in an init.m file once and for all. (Yes, I'm aware this is ugly and hacky, but the other approaches are probably less appealing.)


title: Lazy evaluation/loading of parts of an expression

text: Is it possible to have an expression `x` such that its elements are only evaluated when they are individually accessed, for example when evaluating statements like `x[[1]]` or `f/@x`? The basic idea is that `x` is a list of `Get` commands, each of which loads a large expression (gigabytes), so that `x` can be terabytes in size yet it remains fairly manipulable within Mathematica. What I thought would work was something like:               x={Unevaluated[Get[...]],Unevaluated[Get[...]],...}      The problem with that however is that `Unevaluated` doesn't get stripped when I need it to, i.e. when calling something like `f[x[[1]]]`, because of Mathematica's evaluator semantics. The only workable alternative is to use `Hold` instead of `Unevaluated`, but that requires that I manually call `ReleaseHold` every time, which is ugly. I was hoping for something entirely transparent.


title: Strange behaviour of "Make Table" with exponential function

text: I am trying to create a simple interpolation of `1-Exp[-x^2]` function, over the logarithmic grid, but I am stuck due to some unexpected behaviour:               (*grid creation:*)     grid = Table[10.0^-10*Exp[5*i], {i, 0, 10}];     (*function:*)     am[x_]:=1-Exp[-x^2]     (*grid: function vs. variable*)     Table[{grid[[i]], am[grid[[i]]]}, {i, 1, 10}]      > >     {{1.*10^-10, 0.}, {1.48413*10^-8, 2.22045*10^-16}, {2.20265*10^-6, > 4.85167*10^-12}, >        {0.000326902, 1.06865*10^-7}, {0.0485165, 0.00235108}, {7.20049, 1.}, >        {1068.65, 0.9999999999999999999999999999999999999999999999999......}} >   and here `Table` is stuck. The problem occurs at large values of the variable `grid[[7]]`. It seems like `1-Exp[-x^2]` cannot provide a stable result at large values of the argument. Of course I can define a conditional expression like `If[x>...,1,1-Exp[-x^2]]` but I am eager to know how to treat this problem properly, since I work a lot with such _unstable_ functions and need to to know how to prevent it in the future.


title: Distance to a MultivariateStatistics median

text: I have a population of objects (each of which is described by a list of about a half-dozen real numbers), and I'd like to find some reasonable kind of distance between each of several different test objects and the median of the population, with the goal of being able to say, for example, that because test object A is closer to the median than test object B, therefore A is "more like" the population than B. I believe that I can use the `MultivariateStatistics` package to characterize my population, and then either `SpatialMedian[]` or `SimplexMedian[]` to find a center. So then I need to find a measure of distance from that center to each test object. I gather that a simple `EuclideanDistance` would be incorrect, because I need to account for the ellipsoid's size and orientation (I believe, but I'm not certain, that this is the Mahalanobis distance). I don't see a function in the `MultivariateStatistics` package that lets me find such distances. Is it possible to compute a meaningful distance from a test object to the median of the population that will let me assert whether one test object is "more like" the population than another, and if so, how do I compute that distance? Practical advice would be much better than theoretical. Thanks!


title: need help with finding right syntax for an IF statement

text: I am working with two multi-variable functions `A` and `B`. They depend on some counting factors `n` and `n primed` (integers, larger than, or equal to zero) and additional real variables `x, y, z`. My functions are actually complicated, but for simplicity assume, for example,                A[nn_, np_, x_, y_, z_] := (1/nn + 1/np) (2 x + 2 y + 2 z);           B[nn_, np_, x_, y_,z_] := (1/Factorial[nn] + 1/Factorial[np]) (3 x + 3 y + 3 z);      I would like to use an `If` statement to assign either `A` or `B` to become the definition of a third function `V`. In the example above this is needed to prevent division by zero. I tried different variations of                V[nn_, np_, x_, y_, z_] :=        If[nn > 0 || np > 0, A[nn, np, x, y, z], B[nn, np, x, y, z]];      but I cannot figure out what the correct syntax is. What I would like to accomplish is to use a statement that assigns the expression given by function `A` to function `V` when `n` or `n prime` are NOT zero and assigns function `B` to function `V` when either `n` or `n primed` are zero.


title: How to use legends from PlotLegends in LevelScheme?

text: I've been attempting to find efficient ways to generate graphics with legends for export, and have been working with both `LevelScheme` and the new (to v9) `PlotLegends`. It seems the easiest approach would be to use `PlotLegends` to automatically generate the legends with the graphic, peel out the plots and legends separately, then use `LevelScheme` to arrange/combine as desired. Sounds pretty painless, but... The `RawGraphics` command of `LevelScheme` does not accept MMA's `LineLegend`, etc. objects. The only workaround I've found is to wrap the legend in `Graphics[Inset[...]]`, but this breaks down, as `LevelScheme` dumps these graphics objects in the middle of the `MultiPanel` area. Any ideas on how to get this working (or maybe why it cannot work)? Below is my attempt so far:               Get["LevelScheme`"];          myPlot = Plot[Sin[x], {x, 0, 10}, ImageSize -> 72*3,         PlotLegends -> Placed[LineLegend["Expressions"], {After, Center}]];     Graphics[Inset[myPlot[[2, 1, 1]]], ImagePadding -> None,       PlotRangeClipping -> True]          myDensity =        DensityPlot[Sin[x], {x, 0, 10}, {y, -1, 1}, ImageSize -> 72*3,         PlotLegends -> Automatic];     Graphics[Inset[myDensity[[2, 1, 1]]], ImagePadding -> None,       PlotRangeClipping -> True]          Figure[      {       Multipanel[        {{0, 1}, {0, 1}},        {2, 2},        XPlotRanges -> {{0, 10}, {-1, 1}},        YPlotRanges -> {{-1.1, 1.1}, {-1.1, 1.1}}        ],       FigurePanel[{1, 1}],       RawGraphics[myPlot[[1]]],       FigurePanel[{2, 1}],       RawGraphics[myDensity[[1]]],       FigurePanel[{1, 2}],       RawGraphics[        Graphics[Inset[myPlot[[2, 1, 1]]], ImagePadding -> None,          PlotRangeClipping -> True]],       FigurePanel[{2, 2}],       RawGraphics[        Graphics[Inset[myDensity[[2, 1, 1]]], ImagePadding -> None,          PlotRangeClipping -> True]],       },      PlotRange -> Automatic,      ExtendRange -> {{0.1, 0.1}, {0.15, 0.1}},      ImageSize -> 6*72, Frame -> True      ]      ![enter image description here](http://i.stack.imgur.com/itiPD.png)


title: Map efficiently over duplicates in list

text: I am interested in mapping a function, `f` over a (long) list which contains duplicates. Since this function takes a while to evaluate I would like to make use of this duplication to speed up the mapping. _Attempt_ Let us say my list is               list = {a, a, b, a, c, b}      my purpose is to map `f` over `list` efficiently. I have defined a function               MapDuplicate[f_, list_] := Module[{ff, list1, ulist},     list1 = ff /@ list; (* ff is dummy f *)      ulist = Union[list]; (* the reduced list *)     rr = Dispatch[Thread[(ff /@ ulist) -> (f /@ ulist)]];     list1 /. rr]      which does the trick,               MapDuplicate[f1, list]          (* {f1(a),f1(a),f1(b),f1(a),f1(c),f1(b)} *)      but I strongly suspect there is a more elegant (using `Ordering`? `SparseArray`?) of doing this. _Question_ Any idea on how to do this more efficiently (e.g. without duplicating the list) My apologies in advance if the answer turns out to be trivial.


title: FeynRules Package

text: Does any one use the FeynRules package? If so, how can I implement a vertex of one Gluon and two octet scalars? I tried               LSG := Block[{mu,a},          ExpandIndices[gs S+[a]. G[mu, a1].del[S-,mu]. S-[a2]. f[a,a1,a2], FlavorExpand-> -- ]     ];      but it doesn't work. Also, what should I set in `FlavorExpand ->` ?


title: How to close all other MathKernel before opening the new one?

text: I use `MathLink` to call Mathematica from C program. After any opening to Mathematica, I do close the connection. However, I don't know why some connections are still there. I've been debugging for days but couldn't find the point. Thus, I want to ask if there is any way to close all connection before I open the new one? Seems like not an optimal solution but for now its ok for me. Thanks,


title: How can I find minimum and maximum of a region?

text: I have a regionplot like the following:               m1 = 0.547;     m1p = 0.958;     m2 = 0.137;     r1 = Sqrt[m1^2 + (Sqrt[w1^2 - m2^2] + Sqrt[w2^2 - m2^2])^2] // Expand;     r2 = Sqrt[m1^2 + (Sqrt[w1^2 - m2^2] - Sqrt[w2^2 - m2^2])^2] // Expand;     RegionPlot[      m1p - w1 - w2 < Re[r1] &&        m1p - w1 - w2 > Re[r2], {w1, .1, .25}, {w2, .1, .25},       BoundaryStyle -> Blue, FrameLabel -> {"w1", "w2"}]      How can I find minimum and maximum of w1 and w2?


title: How do you find the frequency and amplitude from Fourier?

text: The problem is that a typical harmonic time history will not have an integer number of cycles in the data. For example, with the following time history you get a numerical Fourier transform.               sr = 400; (* sample rate *)     nn = 200;  (* number of points *)     f = 17.2;   (* frequency in Hz *)     A = 1; B = 0.1; (* Coefficients of Cos and Sin *)     th = N @ Table[A Cos[2 Pi f t] + B Sin[2 Pi f t], {t, 0, (nn - 1)/sr, 1/sr}];     ft = Fourier[th, FourierParameters -> {-1, -1}];     n = Position[#, mx = Max[#]] & [Abs[ft]][[1, 1]];     ListPlot[Abs[ft[[1 ;; n + 10]]], PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/aO6XH.png) This produces a plot with several points making up the peak. The frequency resolution is 2 Hz and there is no point at the harmonic frequency of 17.2 Hz. Clearly the frequency is bracketed between the 9 th and 10 th point (16 Hz and 18 Hz). How do we find the exact frequency and amplitude? I have considered extending by zeros but although this increases the resolution it still results in points on either side of the frequency. Also, I have considered calculating points with non-integer values. However, the resulting spectrum does not have a maximum at the frequency of the time history. My actual data includes noise and other harmonics hence my use of Fourier which is good at concentrating the data I am interested in around a few points in the spectrum. I have worked out one very poor way of finding the frequency and amplitude and will post this when I have worked out how to use StackExchange more fully.


title: What would be a pattern for a general row of an identity matrix?

text: I know this is a novice question but I would like a pattern for a list containing zero or more zeros followed by exactly one 1, followed by zero or more zeros. Something like: {0___,1,0___} But specifying that 0 must be zero.


title: NonlinearModelFit is not giving the fit with minimum chi^2

text: First of all, a bit of background, I am using Mathematica to fit angular distributions of gamma rays, so I apologize for some of the serious messiness in the formulas. The data is simple I have three lists. The first is dataWithErrors = {{x1,y1,dy1}, {x2, y2, dy2}, ... }. The second, rawData = {{x1,y1}, {x2,y2}, ... } is what actually goes to the model fit function. The third is ptWeights={1/dy1^2, 1/dy2^2, ... } Now the code:               P[m_, J1_, sig_]:=E^(-m^2/(2*sig^2))/Sum[E^(-mp^2/(2*sig^2)),{mp,-J1,J1}]     B[k_,J1_,sig_]:=((2*J1+1)^(1/2))*Sum[((-1)^(J1+m))*ClebschGordan[{J1,-m},{J1,m},{k,0}]*P[m,J1,sig],{m,-J1,J1}]     F[k_,L1_,L2_,J1_,J2_]:=((-1)^(J1+J2-1))*(((2*L1+2)*(2*L2+1)*(2*J2+1)*(2*k+1))^(1/2))*ThreeJSymbol[{L1,1},{L2,-1},{k,0}]*SixJSymbol[{L1,L2,k},{J2,J2,J1}]     A[k_,delt_,L1_,L2_,J1_,J2_]:=(F[k,L1,L2,J2,J1]+2*delt*F[k,L1,L2,J2,J1]+(delt^2)*F[k,L1,L2,J2,J1])/(1+delt^2)     ForTransition[k_,delt_,sig_]:=A[k,delt,1,2,17/2,15/2]*B[k,17/2,sig]     (*Constants to account for the detectors not being points*)     saCorr2 = 0.987751     saCorr4 = 0.959561      Now to perform the fit I use the following command:               TransitionFit = NonlinearModelFit[rawData,a0(1 + saCorr2*ForTransition[ 2, delt, sig]*LegendreP[2, Cos[th] ] + saCorr4*ForTransition[ 4, delt, sig]*LegendreP[4, Cos[th] ],{{a0,12544.9},{delt,-1.2395},{sig,1.983}}, th,Weights -> ptWeights, VarianceEstimatorFunction -> (1 &)]      I calculate the reduced chi^2 using:               (Plus@@(((#[[2]]-TransitionFit[#[[1]]])^2/(#[[3]]^2))&/@dataWithErrors)/(16-3)      Dividing by 16-3 because I have 16 points and 3 parameters. Here is the problem, if I run the fit with sig as a free parameter I get a0=12567.8, delt=-1.28286, sig=1.94335, and a reduced chi^2 of 2.912. All of which looks somewhat reasonable. But if I fix sig = 1.983 (and calculate reduced chi^2 exactly the same way) I get a0=12576.4, delt=-1.25549, and a reduced ch^2 of 2.901. If I also fix delt = -1.23947... I get a0=12568.1 and a reduced chi^2 of 2.89344. Finally if I simply calculate the chi^2 with a0 = 12544.9 and delt and sig as above I get a reduced chi^2 of 2.88363. As you can see in the NonlinearModelFit call I give it the ideal values, and it still is not giving those values I realize that these are small differences in the chi^2, but I don't understand why mathematica is doing this. Why is this happening? Are there any suggestions to fix it? Things I can do to improve how my code?


title: How to get dynamic results of the values in three InputFields

text: I have three `InputField`-s which have no initial value. I would like all `InputFields` to have a value in descending order and for each `InputField`, a "right" and "wrong" symbol should be displayed as soon as some value is entered in any of these `InputFields`. The user can enter his first value, say 89 in any of the `InputField` between 100 and 0. It will always show "right" symbol as all other `InputField`-s are empty. If he choose the next `InputField` to be filled in the right hand side of the previous `InputField`, then that value should be between 89 and 0 else it should show wrong dynamically. And If he chooses some other `InputField` to be filled in the left hand side of the first `InputField`, then that value should be between 100 and 89 else it is wrong. ![enter image description here](http://i.stack.imgur.com/SH8WJ.png) I faced the problem when I skipped the first `InputField` and entered 76 in the second `InputField`. It looked alright but as soon as I entered 89 in the third `InputField`, both were shown as wrong.               logicalInputField[i_, numberOfFields_, tx_, symbol_, upperLimit_,      lowerLimit_, noValue_, right_, wrong_] :=        (txtx = tx; sysy = symbol; upup = upperLimit;lolo = lowerLimit; nono = noValue; riri    = right; wrwr = wrong;      Column[{InputField[Dynamic[txtx[[i]]], Number, FieldSize -> 3,         Alignment -> {Center, Center}, ContinuousAction -> True],       ( Dynamic[(  If[txtx[[i]] == Null,    (txtx[[i]] = ""; sysy[[i]] = noValue), (sysy[[i]] = right)    ];                For[j = i - 1, j >= 1, j--, If[txtx[[j]] != "", (upup[[i]] = txtx[[j]]; Break[];),             ""]];           For[k = i + 1, k <= numberOfFields, k++,                      If[txtx[[k]] != "", (lolo[[i]] = txtx[[k]]; Break[];),             ""]];                                               If[txtx[[i]] >= lolo[[i]],                                                                (sysy[[i]] =               right;), (sysy[[i]] = wrong;)   ];             If[lolo < txtx[[i]] <= upup[[i]],                                                         (sysy[[i]] =               right;), (sysy[[i]] = wrong;) ];               sysy[[i]] )    ])   }]) ;                                                               DynamicModule[{s = {}, enterValue = "ENTER", correct = "RIGHT", incorrect = "WRONG"}, For[i = 1, i <= 3, i++,  DynamicModule[{i = i},       AppendTo[s, logicalInputField[i, 3, {"", "", ""}, {enterValue, enterValue, enterValue}, {100, 100,        100}, {0, 0, 0}, enterValue, correct, incorrect]]] ];           Panel[ Row[s, Spacer[0]]]]


Note: Answering my own question as a wiki for future reference. When loading a .Net DLL:               << NetLink`     InstallNET[]     LoadNETAssembly["C:\\Temp\\XYZ.dll"]     NETAssembly["XYZ", 1]      I get the error:               NET::netexcptn: A .NET exception occurred: System.IO.FileLoadException:Could not load file or assembly      file:///C:\Temp\XYZ.dll'or one of its dependencies. Operation is not supported.(ExceptionfromHRESULT:0x80131515) Filename:'file:///C:\Temp\XYZ.dll'--->System.NotSupportedException:An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default,so this load may be dangerous. If this load is not intended to sandbox the assembly....


title: Symbol with Subscript but no quotes in it!

text: If I use the following function to define me a fancy subscript:               Needs["Notation`"];     Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]          SetAttributes[fancySubscript,HoldFirst]          fancySubscript[var_Symbol, tag_String, index_Integer] /;       Not[ValueQ[var]] := Subscript[var, tag <> ToString[index]]          fancySubscript[var_Symbol, tags : {_String ..}, index_Integer] /;        Not[ValueQ[var]] := fancySubscript[var, #, index] & /@ tags          fancySubscript[var_Symbol, tags : {_String ..}, indices : {_Integer ..}] /;        Not[ValueQ[var]] := fancySubscript[var, tags, #] & /@ indices      I can use the following now:               fancySubscript[b, {"b"}, Range@3]      > $\left( \begin{array}{c} b_{\text{b1}} \\ b_{\text{b2}} \\ b_{\text{b3}} \\ > \end{array} \right)$ With the notation module by symbolizing the subscripts: the values are now :               b\[UnderBracket]Subscript\[UnderBracket]DoubleQuote\[UnderBracket]b1\[UnderBracket]DoubleQuote      **1. Problem**   But when I want to refer to such a variable in the list above and write with the shortcuts in a cell by typing `b` then `Ctrl`+`_` then `1`. **The variable is a new symbol because i did not use Quotes ""**               b\[UnderBracket]Subscript\[UnderBracket]b1      How can we circumvent this that I can still write all variables in the cell and they are parsed and interpreted as the one defined in the `fancySubscript` command? It is not so easy because, when I would use something like this:               fancySubscript[b, {b}, Range@3]      I would get an infinite loop, because it is no more a string, hm... **2. Problem:** I cannot assign it back to the variable b:                b=fancySubscript[b, {"b"}, Range@3]      This gives an infinite loop, but when I try this:               btemp=fancySubscript[b, {"b"}, Range@3]     b=btemp      This should work, and not give an inifinte loop, because btemp contains the new defined symbols and they should then be assigned to `b` again, but also here mathematica trys to run a recursion which I dont understand??


title: Any way to reverse span and join two span in Mathematica?

text: I port a matlab code to mathematica. In the original matlab code, I use ":" to pick up the desired elements in a matrix. In mathematica, I find in the documentation that the span operator is ";;" (without quotation). I have a big nx1 matrix (n is odd), the kth element is the very middle element of the matrix, I am going to pick up all element from k with interval 2, I am currently use the following code               M[[k;;1;;-2]]  (* M is the matrix of nx1*)     M[[k+2;;n;;2]] (* M is the matrix of nx1*)      It does return the desired elements; however, I want to maintain one index instead. Is that any way to combine the index such that               idx = REVERSE(k;;1;;-2) JOIN k+2;;n;;2       Also, REVERSE mean to reverse the index programatically.


title: Forcing Mathematica to use certain simplification rule

text: I'm trying to force _Mathematica_ to use following transformation function               tf[e_] :=        e /. {BarnesG[1 + 2 x_] :>           2^(x (2 x - 1)) Pi^(-x - 1/2) (           BarnesG[3/2 + x] BarnesG[1/2 + x] BarnesG[1 + x]^2)/           BarnesG[1/2]^2};      After evaluation of the previous line simplification               Simplify[BarnesG[1 + 2 x],       TransformationFunctions -> {Automatic, tf}]      does not yield desirable result but instead returns original               BarnesG[1 + 2 x]      What am I doing wrong? Any help is appreciated, thank you!


title: Mathematica: computing a difficult integral

text: I am trying to compute the following integral:               Integrate[Exp[Sum[-((cw λ - b[i])^2/(2 σ^2)), {i, 1, n}]], {cw, 0, 1}]      And currently _Mathematica_ outputs > >     (Sqrt[π/2] σ (Erf[(Sqrt[n] (λ - b[i]))/(Sqrt[2] σ)] + >          Erf[(Sqrt[n] b[i])/(Sqrt[2] σ)]))/(Sqrt[n] λ) >   Which is not only blatantly incorrect (there can be no dependence on `i` for example), but also has little connection with my input. If I replace `n` with an integer in the first expression, the output is the correct result for the integration, but I want the general result with `n` summands. What am I doing wrong? **Edit:** I am willing to make assumptions, such as that `λ`, `σ` and all `b[i]`'s are real. Nonetheless, that does not seem to matter here.


title: Can I specify the style of plot for some element in discrete plot?

text: I am using discrete plot to plot a 1D array. But I want to plot some points specified by a span in one style (for example, in red) and the rest points in other style (e.g. in blue).


title: Find sublists of a list that match some conditions

text: Question2::               Needs["TetGenLink`"];     Needs["ComputationalGeometry`"];          long = 100;     broad = 100;     height = 100;          pts = {{0, 0, 0}, {long, 0, 0}, {long, broad, 0}, {0, broad, 0},        {0, 0, height}, {long, 0, height}, {long, broad, height}, {0,          broad, height}};     facets = {{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{1, 5, 6, 2}}, {{2, 6, 7,           3}}, {{3, 7, 8, 4}}, {{4, 8, 5, 1}}};          inst = TetGenCreate[];     TetGenSetPoints[inst, pts];     TetGenSetFacets[inst, facets];          inst1 = TetGenTetrahedralize[inst, "pq1.414a4"];     ElemPtsCoord = TetGenGetPoints[inst1];     ElemFacesMadeofPtsIndex = TetGenGetFaces[inst1];     ElemElemsMadeofPtsIndex = TetGenGetElements[inst1];           Graphics3D[GraphicsComplex[ElemPtsCoord, Polygon[ElemFacesMadeofPtsIndex]]]          ElemPtsCoordandIndex = ElemPtsCoord;     Do[PrependTo[ElemPtsCoordandIndex[[i]], i], {i, 1,         Length[ElemPtsCoordandIndex]}       ];          ElemElemsMadeofPtsIndexandIdex = ElemElemsMadeofPtsIndex;     Do[PrependTo[ElemElemsMadeofPtsIndexandIdex[[i]], i], {i, 1,         Length[ElemElemsMadeofPtsIndexandIdex]}       ];          BoundaryPtsCoordandIndex = GatherBy[ElemPtsCoordandIndex,        (#1[[2]] == 0) || (#1[[2]] == 100) || (#1[[3]] == 0) || (#1[[3]] ==             100) || (#1[[4]] == 0) || (#1[[4]] == 100) &];          BoundaryPtsCoordandIndex = If[        BoundaryPtsCoordandIndex[[1, 1]][[2]] == 0 ||         BoundaryPtsCoordandIndex[[1, 1]][[2]] == 100 ||         BoundaryPtsCoordandIndex[[1, 1]][[3]] == 0 ||         BoundaryPtsCoordandIndex[[1, 1]][[3]] == 100 ||         BoundaryPtsCoordandIndex[[1, 1]][[4]] == 0 ||         BoundaryPtsCoordandIndex[[1, 1]][[4]] == 100,             BoundaryPtsCoordandIndex[[1]],        BoundaryPtsCoordandIndex[[2]]];               BoundaryPtsIndex =        Flatten[Take[BoundaryPtsCoordandIndex,          Length[BoundaryPtsCoordandIndex], 1]];          ClassifiedElements =        GatherBy[ElemElemsMadeofPtsIndexandIdex,         Intersection[BoundaryPtsIndex, Delete[#1, 1]] == {} &]      Introduction: I have a cube sized 100*100*100. and I mesh it with fine mesh. So the total numbers of nodes and elements are huge. and I have to find mesh tetrahedrons which are on the boundary. First, Find points on the boundary faces-> "BoundaryPtsCoordandIndex". Second, Find elements which has any point of "BoundaryPtsCoordandIndex". This is my problem: So the math problem is:               list1 = ElemElemsMadeofPtsIndexandIdex;          list2 = BoundaryPtsIndex;      and Find all sublists of list1 that contain any element of list2 ..?


title: Error message from V6.0.3 on Mavericks

text: With Mavericks, everything works fine except saving documents -- then I get this error: > Internal self test error MacDialog | c | 2 Fixes? Ideas? Any help appreciated.


title: Merging two Lists

text: I have two tables. One is given by               T1 = Table[{x, y, 0.}, {x, 0, V},{y, 0, V}]      and from a calculation I have the second, a list of points {x, y, z}               T2 = {{0, 0, 3.4}, {1, 2, 1.4}, {10, 2, 7.4}, ...}      with `Length[T1] > Length[T2]`. How can I efficiently replace every element `{x, y, 0.}` in T1 by the corresponding point `{x, y, z}` from `T2`?


title: How do I put my packages into Dropbox

text: I don't want to necessarily put my packages in Mathematica's `$UserBaseDirectory`, which is on my local hard drive. Can I somehow tell Mathematica to look for packages in other directories (like DropBox)? Basically, I have two computers running Mathematica -- one at home, and one at work, and would like to be able to work on editing/running my packages on both computers.


title: Replacing High Densities of 1.s in Very Large Binary Arrays

text: I am working with very large binary arrays on the order of {100,100000}. It may look something like this.               data = N[Table[RandomInteger[], {i, 100}, {j, 100000}]];      What I am then trying to do with this data is replace high densities of 1.'s with 0.s in each row. For instance, if I look at successive chunks of 20 in each row and find that it has 15 1.s I want to then make them all 0.s. Now, I know that I can index through each row summing up every 20 indices and determine if the sum is 15 or more. If so, then I can make them all 0. However, indexing through large arrays in this fashion can be very time consuming. Here is a small scale example of what I want to do. In this smaller scale of data I am zeroing out densities of 3 or more for every 5 indices and leaving everything else the same.               data = N[Table[RandomInteger[], {i, 2}, {j, 20}]]          {{1., 0., 0., 1., 0., 1., 0., 1., 0., 1., 1., 0., 0., 0., 1., 1., 0.,        0., 0., 1.}, {0., 1., 0., 0., 1., 1., 0., 1., 0., 1., 0., 0., 1.,        0., 1., 0., 0., 0., 1., 1.}}          Do[     z = Total[data[[i]][[j ;; j + 4]]];     If[z >= 3,      data = ReplacePart[data, Table[{i, j + k}, {k, 0, 4}] -> N[0]]], {i,     1, Dimensions[data][[1]]}, {j, 1, Dimensions[data][[2]], 5}]     data          {{1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 1., 0.,        0., 0., 1.}, {0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1.,        0., 1., 0., 0., 0., 1., 1.}}        I need to find a way to do this as fast as possible with really big arrays. This way takes a long time for a {20,100000} array looking at every 20 indices zeroing out densities of 15 or more. As you can see...               data = N[Table[RandomInteger[], {i, 20}, {j, 100000}]];     Do[     z = Total[data[[i]][[j ;; j + 19]]];     If[z >= 15, data = ReplacePart[data, Table[{i, j + k}, {k, 0, 19}] -> N[0]]], {i, 1,      Dimensions[data][[1]]}, {j, 1, Dimensions[data][[2]], 20}] // AbsoluteTiming          {18.767073, Null}      A {100,100000} array would obviously take longer. I've tried some pattern ideas, see the following Replacing Patterns In a List of Varying Length, but that didn't quite do it since the pattern of 1.s had to be exact before replacing.


title: How to draw hypercube graphs

text: I'd like to draw hypercube projections like those on the Wikipedia page: ![6-cube graph](http://i.stack.imgur.com/QkgTY.png) I tried with               HypercubeGraph[6]      but the graph does not look right; it is not symmetric, it is rotated by some degrees and some vertices that should be merged together (represented on the above figure with different colors) are not. Then I found the Wolfram MathWorld page that suggests `GraphData` might be helpful.               GraphData[{"Hypercube", 6}, "EdgeRules"];     Graph[%]      Produces a similar graph as `HypercubeGraph` but now it is more symmetric.               GraphData[{"Hypercube", 6}, "EdgeList"];     Graph[%]      Produces a different graph, even more symmetric but the vertices are obviously still not merged: ![Mathematica graph](http://i.stack.imgur.com/plUWP.png) Since I'd like to draw several different hypercube graphs manually merging the vertices is not an option. What's the easiest way to draw symmetric hypercube graphs in Mathematica with some vertices merged like in the example from Wikipedia?


title: Connection to remote kernel can not be established - No specific error shown

text: I was trying to set up a remote kernel using Mathematica 8, a Debian server and a Mac OSX 10.8 client. First I configured a VPN connection between server and client and went through all the basic steps of the remote kernel setup (registration of SSH keys etc.). However, every time Mathematica tried to connect to the remote kernel, I was asked for the passphrase 5 times and then the connection failed to be established. Connecting directly from the terminal worked just fine, so the passphrase was definitely correct. The auth.log on the server side told me the key was accepted, but the connection was closed by the client shortly after. I then tried to connect calling the Mathematica SSH implementation directly from the terminal. I was asked for server, username, keyfiles and passphrase however no matter what I typed in there, the error was exactly the same even if I used just made up stuff - exception handling and logging does not seem to be the favorite thing of the Wolfram engineers. Changing to the default SSH implementation in launch command didn't change things either.


title: Optimize recurrence output

text: I have recurrence and I need to calculate first $N$ members of the sequence               ClearAll[aa];     l=3;     aa[n_, l_] := If[n <= l,         Quotient[n, l],        (l + 2 (n - l) aa[n - l, l] + (n - l) (n - 1) aa[n - 1, l])/(n*(n + 1 - l))     ]          Table[aa[i, l], {i, 0, 30}] // AbsoluteTiming      I guess it is stupid to use `Table` since its recalculate some of the members several times. How I can output all members in one pass? Can I use `RecurrenceTable` in this case and is it the quickest way to do it?


title: Mathematica won't maximize my function

text: I'm trying to maximize two functions. For the first one, the code runs correctly and returns the desired answer               Maximize[{         ax (Log[a] - Log[ax + cy]) +          bx (Log[b] - Log[bx + dy]) +          cy (Log[c] - Log[ax + cy]) +          dy (Log[d] - Log[bx + dy]),         x >= 0, y >= 0, x + y == 1       },        {x, y}]      > >     {ax Log[a] + bx Log[b] + cy Log[c] - ax Log[ax + cy] - cy Log[ax + cy] + >           dy Log[d] - bx Log[bx + dy] - dy Log[bx + dy], >      {x -> 1/2, y -> 1/2}} >   But for the second one,               Maximize[{         (1/2) (x Log[x] + y Log[y] + u Log[u] + v Log[v]) -          (1/2) (x + u) Log[(1/2) (x + u)] -          (1/2) (y + v) Log[(1/2) (y + v)],          x >= 0, y >= 0, u >= 0, v >= 0,          x + y == 1, u + v == 1       },        {x, y, u, v}]      I just get the same thing I wrote as an input What I'm I doing wrong? How should I fix it?


title: How to wrap this dynamic code inside a Manipulate?

text: My goal is to set up a Ising-type simulation, where many fast simulation steps are done in the background, and a visualization of the current state is displayed as the simulation evolves, being updated once or twice per second. I manage to do that by displaying an image of the system inside `Dynamic`, and having the image being refreshed regularly inside a scheduled task (`RunScheduledTask`). The simulation itself happens in a long `Do` loop, and its parameters vary by being `Control`'s. Here's the full code I designed for that:               L = 100;     sys = 2*Array[RandomInteger[] &, {L, L}] - 1;     img = Image[sys, Magnification -> 2];     Column[{       Row[{"Temperature: ", Control[{{temp, 2.0}, 0.1, 4.}]}],       Dynamic[img]       }]     RemoveScheduledTask[ScheduledTasks[]];     RunScheduledTask[img = Image[sys, Magnification -> 2], 0.5];          Do[      {i, j} = RandomInteger[{1, #}] & /@ Dimensions@sys;      dE = 0; s = sys[[i, j]];      If[i > 1, dE += sys[[i - 1, j]]]; If[i < L, dE += sys[[i + 1, j]]];      If[j > 1, dE += sys[[i, j - 1]]]; If[j < L, dE += sys[[i, j + 1]]];      dE *= 2*s;      If[dE < 0 || RandomReal[] < Exp[-dE/temp], sys[[i, j]] *= -1];      ,      {1000000}]     RemoveScheduledTask[ScheduledTasks[]];      ![Snapshot of Ising simulation running](http://i.stack.imgur.com/R02Ad.png) (the entire code inside the `Do` loop is the physics of the system. If you don't know what an Ising model is, you can safely ignore it. I included it to post a self-sufficient code.) * * * The above may not be pretty, because it's the first time I do these things, but it does work. However, I cannot export it into a working CDF file, because the doc says: > Use the Manipulate command to generate interactive content controlled by > mouse-driven actions. I've spent an hour or so trying to wrap the whole thing in a `Manipulate`, but it doesn't work. The best I could do was to split it up, like that:               Manipulate[      img = Image[sys, Magnification -> 2]        Do[         {i, j} = RandomInteger[{1, #}] & /@ Dimensions@sys;         dE = 0; s = sys[[i, j]];         If[i > 1, dE += sys[[i - 1, j]]]; If[i < L, dE += sys[[i + 1, j]]];         If[j > 1, dE += sys[[i, j - 1]]]; If[j < L, dE += sys[[i, j + 1]]];         dE *= 2*s;         If[dE < 0 || RandomReal[] < Exp[-dE/temp], sys[[i, j]] *= -1];         , {1000000}]      ,      {temp, 0.1, 4.},      Initialization :> (L = 100;        sys = 2*Array[RandomInteger[] &, {L, L}] - 1;        RemoveScheduledTask[ScheduledTasks[]];        RunScheduledTask[img = Image[sys, Magnification -> 2], 0.5];)     ]      which partly works, because some time I get an image displayed, but the slider doesn't seem to control anything. So the question is: how would you advise me to transform the first sample of code into something that can be exported to CDF? Am I at least on the right track?


title: SaveDefinitions->True changes the displayed image

text: I have a `Manipulate[ ]` that displays an image with a superimposed `Locator` object. It works fine when I have `SaveDefinitions->False` but when I try to change `False` to `True` the image object changes (and is not displayed correctly). Here's an image which I load in and call `img` ![my tif image](http://i.stack.imgur.com/xKudh.png) The Manipulate is this:                img = Import["http://i.stack.imgur.com/xKudh.png"];      Manipulate[img, {p, Locator}, SaveDefinitions -> False]      If you evaluate this, it displays the image with a locator object in the bottom left. All is well. But if you now evaluate                Manipulate[img, {p, Locator}, SaveDefinitions -> True]      it displays not the image, but a long list of numbers starting with:               Image[{{244,243 ....      In trying to debug, I note that `ImageQ[img]` is `True` after evaluating the first `Manipulate` but is `False` after evaluating the second. This does not occur with all images (I tried a jpeg) but seems to happen with my .tif files (like the one above). _Mathematica_ 9.0.1 Mac OS. I just noticed that when I uploaded the image, it was converted to a .png file. The same (bad) behavior occurs with this file as well.


title: Histogram with a logarithmic scale for the y-axis

text: How can I get a histogram with a logarithmic scale only on the the y-axis? With               data=RandomReal[NormalDistribution[0, 1], 200]          Histogram[data, {"Log", 10}, "LogCount"]      I get a log scaled histogram for both axis. I'm using mathematica 7.


title: Efficiently keeping elements in a list (an input list) that exist in another list (a keep list)

text: I have some code that generates lists of integers (one such list is called, for example, `inputList`). I also have a "master list" of integers that should be kept, if present, in `keepList`. I would like to write a function `keepElements` that keeps integers in `inputList` that exist in `keepList`. Alternatively, I could write a function `removeElements` that removes elements from `inputList` that do _not_ exist in `keepList`. Since `keepElements` and `removeElements` generate the same output list, I will use whichever is faster. Below is a sort of minimal working example. In the first section of code, I generate `inputList` and `keepList` (I have used `RandomInteger` in this example, just to generate `keepList`). Note that even in my actual code, `inputList` and `keepList` are both in sorted ascending order. I have written `keepElements` and `removeElements`, but I am wondering if you can please help me make them faster. I will need to run either function approximately 200,000 times, so this can quite expensive and I would like to minimize the cost as much as possible. Do you have any advice? Using `Position` is probably relatively expensive, so I should perhaps avoid using it. Thank you for your time!               minVal = 1;     maxVal = 1000;     inputList = Range[minVal, maxVal];     keepList =        DeleteDuplicates[        Sort[Table[RandomInteger[{minVal, maxVal}], {500}]]];          keepElements[inputList_, keepList_] := Module[{position},       position =         Flatten[Position[inputList, _?(MemberQ[keepList, #] &), {1},           Heads -> False]];       inputList[[position]]       ]     keepElements[inputList, keepList] // Timing // First          removeElements[inputList_, keepList_] :=       DeleteCases[inputList, _?(! MemberQ[keepList, #] &)]     removeElements[inputList, keepList] // Timing // First      which on my machine gives the output: > 0.031 > > 0.016


title: NIntegrate - WorkingPrecision

text: I am trying to `NIntegrate` this expression. It is very close to `zero`, and so gives all possible types of errors. More precisely, I am actually solely interested in the `Sign` of the outcome. However, this sign changes for different options:               NIntegrate[(1/(108 π))E^(-((2 Pq^2)/9)-1/18 (53-16 Pq+2 Pq^2)^2) (12+         E^(1/18 (53-16 Pq+2 Pq^2)^2) Sqrt[2 π] (9-4 Pq^2)-E^(1/18 (53-          16 Pq+2 Pq^2)^2) Sqrt[2 π] (-9+4 Pq^2) Erf[(-53+16 Pq-2 Pq^2)/(3 Sqrt[2])]),      {Pq,-∞,∞},      WorkingPrecision -> 20, AccuracyGoal -> 10]     (* -1.7126730471588308508*10^-16 *)          NIntegrate[(1/(108 π))E^(-((2 Pq^2)/9)-1/18 (53-16 Pq+2 Pq^2)^2) (12+         E^(1/18 (53-16 Pq+2 Pq^2)^2) Sqrt[2 π] (9-4 Pq^2)-E^(1/18 (53-          16 Pq+2 Pq^2)^2) Sqrt[2 π] (-9+4 Pq^2) Erf[(-53+16 Pq-2 Pq^2)/(3 Sqrt[2])]),      {Pq,-∞,∞},      WorkingPrecision -> 30, AccuracyGoal -> 10]     (* 8.61998254998083821843412792489*10^-16 *)      Any ideas how to make this `NIntegrate` work without errors, while at the same time being confident in the `Sign` of the outcome? Thanks! Laurens


title: How to copy a function by value?

text: I need to change a function symbol multiple times by assigning another symbol to it, but when I'm trying to do that the symbols overwrite each other. I'm assuming this is because the assignment is by reference. For example, this input:               func1[x_] := x^2     func2 = func1; func3[x_] := func1[x]     {func1, func2, func3}     {func1[#], func2[#], func3[#]} &[4]     func1[x_] := -x     {func1[#], func2[#], func3[#]} &[4]      Gives the following output:               Out[]= {func1, func1, func3}     Out[]= {16, 16, 16}     Out[]= {-4, -4, -4}      How could I make the assignment so changing one function doesn't influence changing the other?


title: View the FullForm of ^^

text: Why am I unable to see the `FullForm` of `^^` (the shorthand notation for `BaseForm`)?               FullForm[HoldComplete[16 ^^ 2]]     (* HoldComplete[2] *)          FullForm[ToExpression["HoldComplete[16 ^^ 2]"]]     (* HoldComplete[2] *)          Trace[HoldComplete[16 ^^ 2],TraceInternal->True]     (* {} *)      My only clue is from the Possible Issues section on `HoldComplete`: > HoldComplete affects only evaluation; input transformations are still > applied: Is there a way to see the `FullForm`?


title: How to set return type of `InterpolatingFunction ` in compile

text: Consider this               s = C1 /.        First@NDSolve[{I C1'[t] == C2[t] E^(-I t),           I C2'[t] == C1[t] E^(I t), C1[0.] == 1., C2[0.] == 0.}, {C1, C2}, {t, 0., 10.}]     sol[t_] :=       Piecewise[{{s[t], t <= 10.}, {Sin[t], t <= 20.}, {Cos[t], t <= 30}}, 0.]     On["CompilerWarnings"]     f3 = Compile[{{t, _Real}}, Evaluate@sol[t]]      I get warnings because compile doesn't know the return type of `InterpolatingFunction` > Compile::noinfo: No information is available for compilation of > InterpolatingFunction[{{0.,10.}},{4,31,1,{107},{4},0,0,0,0,Automatic},<<1>>,{Developer`PackedArrayForm,{0,2,4,6,8,10,12,<<38>>,90,92,94,96,98,<<58>>},{1. > +0. I,0. +0. I,1. +0. I,-0.000102139+0. I,1. +1.06555*10^-12 > I,<<42>>,-0.5557+0.183522 I,0.767381 +0.0556081 I,-0.598783+0.22247 > I,<<164>>}},{Automatic}][t] . The compiler will use an external evaluation > and make assumptions about the return type. >> and it failed to use the compiled version               f3[5.]      > During evaluation of In[38]:= CompiledFunction::cfex: Could not complete > external evaluation at instruction 3; proceeding with uncompiled evaluation. > >>               (*-0.787326 - 0.231525 I*)      so I tried to set the return type like this               f3 = Compile[{{t, _Real}},        Evaluate@sol[t], {{_InterpolatingFunction, _Complex}}]      or               f3 = Compile[{{t, _Real}}, Evaluate@sol[t], {{InterpolatingFunction[__], _Complex}}]      both don't work. In contrary, `Fourier` seems also has this problem(example taken from here)               Compile[{{m, _Real, 2}}, Fourier[m]][Table[N[i - j], {i, 2}, {j, 2}]]      > CompiledFunction::cfex: Could not complete external evaluation at > instruction 1; proceeding with uncompiled evaluation. >>               (*{{0., 1.}, {-1., 0.}}*)      but after specify the return type, it works               Compile[{{m, _Real, 2}}, Fourier[m], {{_Fourier, _Complex, 2}}][Table[N[i - j], {i, 2}, {j, 2}]]     (*{{0. + 0. I, 1. + 0. I}, {-1. + 0. I, 0. + 0. I}}*)      So how should I specify the return type of `InterpolationFunction`?


title: Transforming a mutiplication into an addition

text: How can I force _Mathematica_ to transform               5a      into               a+a+a+a+a


title: string to complex number

text: Consider the following list               MyList= {-0.0000396, -0.0000187167, "0.10259130990561813-0.0677132394802944i"}          Head /@ MyList (* -> {Real, Real, String} *)      In fact, the `String` is a complex number. Is there an easy way of converting `MyList` to `MyNewList` such that               Head /@ MyNewList (* -> {Real, Real, Complex} *)


title: Comment color in a notebook

text: My requirement:   1. Comments should appear within a notebook in blue and font size 12 and in Courier by default.    2. This should work on not just my machine (by tweaking the preference of MY _Mathematica_ )    3. I could use this code but the problem is when I open the notebook, the comments are still in gray.              SetOptions[EvaluationNotebook[], AutoStyleOptions -> {"CommentStyle" -> {FontColor -> Blue,        FontFamily -> "Courier", FontSize -> 12, FontWeight -> Bold}}];       Once I evaluate this cell, it turns blue. I would like to have it in this format even before I evaluate anything. I am looking for something where just by opening this notebook, it will by default evaluate this cell or something like that, but machine independent?   4. I could simply use cell style as "Text" and have it formatted. However, the problem is, I cannot divide cells within a function and if I need to put in comments within a function is not possible to use the cell style as "Text".


title: About doing an sum

text: I want to explain this summation to _Mathematica_ , For $a >0$ define $n_u, n_d \in \mathbb{Z}$ such that if $\{ a \} \leq 0.5$ then $n_u = [a]-1$ and $n_d = - [a]$ and if $\{ a \} > 0.5$ then $n_u = [a]$ and $n_d = -([a]+1)$. Now compute the sum, $\sum _ {n = n_d} ^{n_u} (1+2n)Log[a^2 - (n + \frac{1}{2} )^2] $ Can someone help me write this in _Mathematica_? * * * Withe everything that I tried so far, _Mathematica_ produced a complex number as the answer! I don't know how _Mathematica_ is adding up a finite number of real numbers to get a complex number!


title: Gram-Schmidt process with Hermite functions on [-1, 1]

text: Denote by $h_n$ the $n$-th Hermite function. $$ h_n(x) = \frac{(-1)^n }{\sqrt{2^n n! \sqrt{\pi}}} \mathrm{e}^{\frac{x^2}{2}} \frac{\mathrm{d}^n}{\mathrm{d} x^n} \mathrm{e}^{-x^2} $$ I am trying to find the 40th, 41st and 42nd terms in Gram-Schmidt process with Hermite functions $h_n$ on $[-1, 1]$. I've used the usual procedure for Gram-Schmidt process, but I've been able to calulate only the first 6 terms and then my computer got stuck. Is there some way to calculate them?


title: Summing Normal random variables

text: I would like to plot the graph of the sum of two random variables.So, I wrote               Plot[PDF[NormalDistribution[0, 1]+NormalDistribution[0, 1], x], {x, -10, 10}]      Why doesn't it work?


title: Overlay alignment

text: Borrowing `triangularArrayLayout` from here, I have:               triangularArrayLayout[triArray_List, opts___] :=       Module[{n = Length[triArray]},        Graphics[MapIndexed[         Text[Style[#1,             Large], {Sqrt[3] (n - 1 + #2.{-1, 2}), 3 (n - First[#2] + 1)}/            2] &, triArray, {2}], opts]]          n = 6;     s = 500;     coeffs = triangularArrayLayout[Table[Row[{"C(", i, ",", j, ")"}], {i, 0, n}, {j, 0, i}],         ImageSize -> s];     tri = triangularArrayLayout[Table[Binomial[i, j], {i, 0, n}, {j, 0, i}],         ImageSize -> s];     layers = {Overlay[{coeffs, Show[tri, TextStyle -> GrayLevel[.8]]}, Alignment -> Top],         Overlay[{tri, Show[coeffs, TextStyle -> GrayLevel[.8]]}, Alignment -> Top]};          Manipulate[layers[[u]], {{u, 1, " "}, {1 -> "binomial coefficients",         2 -> "Pascal's triangle"}}, ControlType -> RadioButtonBar]      but the vertical alignment is off: ![Mathematica graphics](http://i.stack.imgur.com/fZooA.png) ![Mathematica graphics](http://i.stack.imgur.com/L0LM5.png) This is the main issue, but I am also curious how to:   1. typeset the $C(n,r)$ as `TraditionalForm` (with the varying $n$ and $r$ values throughout)   2. typeset the $C(n,r)$ as $_{n}C_{r}$ (also with the varying $n$ and $r$ values).


title: How do I plot the differential of this function?

text: Suppose I have this function: $$z(x,y) = \left| \frac{ \frac{1}{3x +iy} -2x}{iy + \frac{1}{x}} \right| $$ I want the contour plot of $\frac{\partial z}{\partial x}$ with axes $(x,y)$. Tried this code, but didn't work.               z = Abs[ ( (1/3 x + I y) - 2 x )/ (I y + 1/x) ]     ContourPlot[D[z[x, y],x], {x, -2, 2}, {y, -2, 2}]      This seems rather straightforward, so I'm not sure what I'm missing.


title: How to get vector length?

text: Is there any built-in function in Mathematica, to get vector length? So I don't have to do this `Sqrt[v[[1]]^2 + v[[2]]^2 ]`


title: WindowSize error message when saving Graphics object as PNG

text: When I try to save a `Graphics` object using the menu File ▶ Save Selection As... or via right click and Save Graphic As... the Messages window pops up with the following error message:               The specified setting for the option WindowSize cannot be used.      Than I tried to use WindowSize, but I can't get any output if I add WindowSize to               Graphics3D[{Arrowheads[Small],        MapThread[Arrow[{#1, #2}] &, {tockez0, 10^(11) poljez0 + tockez0}]},       BoxRatios -> {1, 1, 1.5}, Axes -> True, AxesLabel -> {x, y,}]      Anything I can do? :/ I want to save it in any format that LaTeX can work with, I prefer .PNG


title: Problem solving a Fredholm integral equation

text: Based on the algorithm by PlatoManiac presented here Integral equation numerical solution with NDSolve I am solving a Fredholm integral equation with the following constants and arguments:               n=1     a=0.     b=1.     θ=45.     lambda=-1.     Kpart[A_?NumericQ][x_,y_]:=(A/2)*(BesselJ[1,A*(x+y)]-BesselJ[1,A*Abs[x-y]]-I*StruveH[1,A*(x+y)]+I*StruveH[1,A*Abs[x-y]])     Gpart[A_?NumericQ][x_]:=Sin[x A Cos[θ Degree] Degree]/(A Cos[θ Degree])     f2[A_?NumericQ,x_?NumericQ]:=FredholmKind2[{a,b,lambda,Kpart[A],Gpart[A]},n,Method->Automatic][x]     Ks=Table[{A,NIntegrate[x f2[A,x],{x,0,1}]},{A,0,6,0.1}]      I am doing something wrong and I get 'SetDelayed::write: "Tag Times in ((1.41421 Sin[0.0123413 A A_?NumericQ])/A)[x_] is Protected.' and 'NIntegrate::inumri' errors. Can you please help me see what's wrong with the algorithm?


title: Label names within Manipulate with ControlType->RadioButton

text: I modified an example from the documentation to have a `RadioButton` control over a specific list of values:               Manipulate[Plot[Sin[a x + b], {x, 0, 6}], {{a, 2, "Multiplier"}, {1, 2}}, {{b,         3, "Phase Parameter"}, {3, 4, 5}}, ControlType -> RadioButton]      ![Mathematica graphics](http://i.stack.imgur.com/SsyIz.png) However, in place of 1, 2, 3, etc. I'd like textual labels (but still need to pass those specific, discrete numeric values to the object inside the `Manipulate`). In the spirit of the _Multiplier_ textual label, I tried               Manipulate[Plot[Sin[a x + b], {x, 0, 6}],        {{a, 2, "Multiplier"}, {{1, "cat"}, {2, "dog"}}},        {{b, 3, "Phase Parameter"}, {3, 4, 5}}, ControlType -> RadioButton]      to no avail: ![Mathematica graphics](http://i.stack.imgur.com/Grd6C.png) How do I get the appearance (and behavior) here that I am after?


title: Adjust the opacity of the lines in a ListPlot

text: Here is what I am trying to plot:               randomWalk := NestList[# + RandomReal[{-1, 1}] &, 0, 1000];     Show[Table[ListPlot[randomWalk, Joined -> True], {100}], PlotRange -> Automatic]      Which gives: ![enter image description here](http://i.stack.imgur.com/eI1Fj.png) What I'd like to do is give the lines a bit of transparency so that it is clearer to see the density of the plot at various areas; i.e. the darker the area, the more overlapping lines there are at that point. Since this is a `ListPlot` though, how can you change the properties - i.e. opacity - of the lines?


title: NSolve transcendental equations

text: NSolve[{Cos[al] == R/(0.0496045\[VeryThinSpace]+ R),       Cos[al + 0.1/R] == R/(0.05\[VeryThinSpace]+ R)}, {al, R},Reals]      It is not solving, something missing here.


title: How to determine all possible functions/symbols that can be accessed from a Mathematica installation?

text: I made a list of all symbols and functions that can be accessed from Mathematica and any included package that comes with it after standard installation. I thought I managed to get a list of everything possible. But I just found out I missed this `TetGenLink`               Needs["TetGenLink`"]      Works and loads many functions. The strange thing is that I do not see this package anywhere on my V9 installation. (I found all packages by manually looking in each folder under the installation, and checking all files for packages) i.e. under `AddOns` and `SystemFiles` etc.. to make sure I do not overlook anything, so I thought I got everything. Looking at TetGenLink link it says `TetGenLink is a Mathematica application that uses Wolfram LibraryLink to link to TetGen functions` What does this actually mean? What is a `Mathematica application`? I went now looked at LibraryLink and it says `Wolfram LibraryLink provides a powerful way to connect external code to Mathematica` So, if I do `Needs` and I do not have access to the internet, then I can't use these functions?. No. I just did a quick experiment: I shut down my internet connection, closed Mathematica, started it up and did `Needs["TetGenLink`"]` and it worked! So I am more confused now where is it loading this from. **My question really is** : How do I make sure I have a list of all possible symbols/functions that one can reference from a Mathematica session? where else to look to make sure I find other missing functions like the above? It seems I need to find out what other such Mathematica applications are out there and add them to the list. FYI, the current list I have is here (I need to go update it now to add these new functions). I am not sure now if there are more things like this that I overlooked. I'd like to have everything in the list. Also, if someone sees something I am missing, please let me know. thanks, **update** I found it ! They are in the `SystemFiles\\\Links\\\` folder, and I did not look there since I never thought there are packages there to use. I see that I overlooked many. This means a long night for me to update the list. But good to find these, I never knew about these before. Still if someone think I missed something more, please let me know. ![enter image description here](http://i.stack.imgur.com/o6H9p.png) **Update 12/4/12** Ok, I just added all those `applications`, rebuild the tables and uploaded them here These are the new stats on V9               92     different contexts      7,919  total symbols (names and functions) in all known packages and contexts     4,153  total functions


title: Assumptions are not being applied to integral

text: I am trying to use assumptions to simplify an integral, but I can't seem to get the assumptions to apply themselves. Here is the code I am using: ![my code](http://i.stack.imgur.com/NXOib.png) Note the expressions in the assumption can be found in the answer. Am I doing something wrong? Is there a proper way of using assumptions? I read through the _Mathematica_ tutorial for assumptions but that seems to have confused me more.


title: How to prevent conversion of number forms to numbers in Import [ webpage, "Data" ]?

text: I have tabular data on a webpage. It looks like this:               Import["http://mfvonh.me/numericalTable.html", "Plaintext"]      > 1.0 > > 1.1 > > 3.53 However, I have many columns, so I want to import it using `"Data"`:               Import[ "http://mfvonh.me/numericalTable.html" , "Data" ]      > { 1. , 1.1 , 3.53 } I'd like to prevent `Import` from converting number-like forms to numbers, as it has done above, and simply extract all tabular data as strings. Obviously there are easy ways to hack this with a workaround; I am looking for an answer that involves `Import[ _ , "Data" ]`. I assume this conversion is somewhere in the `Trace`, but I was overwhelmed when I tried to look at it:               (Import["http://mfvonh.me/numericalTable.html", "Data"] //        Trace) >> "trace.txt"      produced **26 megabytes** of plain text. I took a look. Now I'm stuck.


title: Getting a usable expression tree

text: I need to get the expression tree for some expression.               expr //TreeForm      The above grabs the expression tree but it isn't in some sort of usable format. Just an image.               Level[expr, {-1}, "Heads"->True]      This does a depth first traversal of the expression tree and does give me a list of all items in the expression tree. The issue with this is that:               expr = a+b*3*c+d     Level[expr, {-1}, "Heads"->True]     {Plus, a, Times, 3, b, c, d}      and now you can see that because of the location of d I have no information on what goes where with Levels. So the question is, is there a way for me to get the expression tree in some format where I can actually tell where everything is supposed to go? Acceptable formats would be of the form of {operator/operatorFunctionName, symbol/value, {operator/operatorFunctionName, symbol/value, {... continues as far as can go}}, moreSymbolsRelatedToFirstOperation} OR {operator/operatorFunctionName, operator/operatorFunctionName, ...} {{symbol/valueForFirstOperator, ...}, {symbol/valueForSecondOperator,...}, ...} OR any other similar format.


title: ListDensityPlot controlling the number of colors

text: Is there a way to set the number of colors used in ListDensityPlot. I am using "Rainbow" as follows:               ShowLegend[     ListDensityPlot[TestList, ColorFunction -> "Rainbow"],     {ColorData["Rainbow"][1 - #1] &, 10,      ToString[LMax], ToString[LMin], LegendPosition -> {1.1, -.4}}]      TestList is a list like {{x1,y1,z1},{x2,y2,z2},...} In the Legend, to get 5 colors, I can change the 10 above to 5, and I get 5 colors. I would like to do the same in ListDensityPlot as well and get 5 colors. Can someone tell me how to do this? Thanks. Shrihari


title: Have I found a bug in Integrate?

text: The following command gives `0` in _Mathematica_ 9.0.1.               f[a_, b_] := Exp[I*(a*x^3 + b*x^2)];     Integrate[f[a, b], {x, -Infinity, Infinity}, Assumptions -> {a > 0, Element[b,Reals]}]      This seems to be wrong, see the following article:   http://www.walkingrandomly.com/?p=5031 Is this really a bug and if yes, is it known (is it perhaps even some instance of a bigger problem)?


title: How to do substitution of variable with power in Mathematica?

text: I want to replace $x^{i+1}$ with $z_i$. EDIT: I have some latex equations, and wish to import them to MMa. How to replace x_i (NOT $x_i$) with $x[i]$ But it seems the underscore "_" has a special meaning (function), can we do such substitution in MMa? **EDIT2:** For example, I want to convert the following two latex equations:                       `{la_3^2=0, la_1la_3-6la_3ps=0}`      into                       `{la[3]^2==0, la[1]*la[3]-6*la[3]*ps==0}`      so that I could apply Simplify or Solve to these equations later. Great thanks.


title: Solve huge symbolic system of linear equations

text: I have a system of 76 symbolic linear equations (i.e. some coefficients are symbolic) with a sparse coefficient matrix. However, neither `Solve[]` nor `LinearSolve[]` can solve this system in a reasonable amount of time (I have not received an answer in an hour). On the other hand, Maple gives me the correct answer in a few seconds. The 76 linear equations `$equations` in 76 `$coefficients` are (also can be found here.):               $equations = Uncompress["1:eJztXUuPHVcRdsbxOCCEEIsIKRISWURZzu3nDHt2WaCIP2BQLFkYInDy570IzNx+1a3qOqe+73S3HeVmYcczp/q8qurUu/709++/ff3Ns2fP3n36+Mc3b9798Prm6V8vHv/4y39+fPX29e+nX/717Y/vll/+7c2/vhv/+dnjH9+++uHN9/9+9fbN/x7/e3P+8fPHP15VNQ7SwyDNHQ5SvX5+ASJ+\ 1/Xvnv7xXauGeF99LrZ7hvyn/ngAsg9DfvL4DwFZP7CQzR0NWbH7bO8xyFtztjUO2WOQ9mwDkOcTWuaczpaArDBIe7b160891B6HfNe+e/n0s3+8evvqv3dvHv/3mab7L5/hdL8s5aSJ+DxgvI5T/nPqTKomuAIB0sIgdZSNCJDAwtRe6i4P8tPlaTb4LM0DDNLiJ9Z2MHqfRmI8wZBVE4Y0uMBC1nc\ 0ZHy1BkHYORt6zuaBhWzps23j+/xJcxf6KWhYtjzhEA5Z009BHV+txr4uDPn0kwtew87ZxB9LjQn02bbzPtVz8/RyDV8D3zDJqeCN8MxtQekNNqKJu8H5Ac1rF/xRy7wt2sOpQu7v5rwS/BIqYtfDXOxxnUBpz0xZZyW53xFUsEiMYaFIgAQkHK2OBcQVBRKWPYQ4Tys8Ez8lVKUTqyo1ccVOK1n0nC\ 24z01eufhbpU/odMBbpZUses75rbpSaVrpjlOphoxjr4NJBH3T5heASjUkuE+KSnmJ0uGAhCkElCgpKvUkylUq/XWCSoWJo8ZtmC1Owa0WUM960mjDrNZt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q+plBaIvwQ/UsLpFC+CTm9z02r55uC9jjp8klTO4bvRarnG5BS7rVurPi8aCORVGtFfB2emhnpR6nTgaMiuliYfoSFGNBDDeZGIQ2+446Oke6YOnZS9CXwqqMj1zsal3t+tUxFuouz/UjbW2ryosM35vzwHTh3p/WzCEgpMezBuTucc/PY3jlvKR+vPDzRRLI4FLE8\ zkKLhDRjKUg1dYMN/g/TGBw4"];     $coefficients = Uncompress["1:eJwtzLtNQ1EQRdEnoBE6sOd3TQ+O6AACJCKCR//C4q5k9iRnvX7+vH/dj+M4Xx7n/n3+nk+P5+Oyc92Jndypnd6ZnbVz23k7n//nF71qaGpp6+jSm/KCF7zgBS94wQte8IIXvOQlL3nJS17ykpe85CWveMUrXvGKV7ziFa94xWte85rXvOY1r3nNa17zhje84Q1veMMb3vCGN7zFW7zFW7zFW/0H\ Ks1gug=="];      and I try the following code to solve:               $result = Solve[$equations,$coefficients]      or               $matrix = CoefficientArrays[$equations, $coefficients];     $result = LinearSolve[$matrix[[2]], $matrix[[1]]]        Is there any way to solve this system with Mathematica in a reasonable amount of time?


title: Incrementing a number where each digit has a different base

text: Let's say I have a list, for instance {10,5,3}, indicating the bases for each digit of my 3-digit number. Using this basis, if I wanted to increment {8,4,1} a couple of times, here's what I would get:               {8,3,1} -> {9,3,1} -> {0,4,1} -> ... -> {9,4,1} -> {0,0,2} -> and so on      Now I can go ahead and do this using loops like one would normally do. But I'm sure there's a more elegant way of implementing this using some of Mathematica's already existing functions. Can anybody think of a sleek way to do this? Thanks in advance,


title: Mathematica Mac Keyboard Shortcuts not Working?

text: Really I'm just trying to use the `Ctrl`+`2` shortcut to make a radical, but for some reason this won't work. What could possibly be going wrong? The exponent shortcut works (i.e. `Ctrl`+`6`).


title: Why is multidimensional Reverse slow?

text: I have found that multidimensional `Reverse` is ~10 times slower than exact `-1 ;; 1 ;; -1`:               n = 1000;     mat = RandomReal[1, {n, n}];          mat2 = Reverse[mat, 2]; // AbsoluteTiming     mat3 = mat[[All, -1 ;; 1 ;; -1]]; // AbsoluteTiming     (* {0.088234, Null} *)     (* {0.006836, Null} *)          mat2 == mat3     (* True *)      Why? Is it a bug? Both produced arrays are packed. I use _Mathematica_ 9.0.1 on Linux. _Mathematica_ 8 has the same problem. * * * Reply from the Wolfram Technical Support: > Thank you for your message. > > I could reproduce this performance issue on Mathematica 9. > > I have filed a report on this to our database and thank you for bringing > this issue to our attention. * * * **Edit:** _Mathematica_ 10.0.0 has the same problem...


title: A Sierpinski-ish structure, via 2D automata

text: The project is originally based on a puzzle proposed by EIORU at http://www.ptt.cc/bbs/puzzle/M.1342451949.A.00F.html (若您懂得讀中文 / if anyone happen to read Chinese^^) last July. The descriptions, simply put, are as follows: >   1. Initially on a x-y plane at the origin there's a vertical **stem** , > length = 1. >   2. The stem grow two **twigs**. One to the east and the other to the west. > the twigs are of 45° polar angle, length = $\sqrt{2}$. Now the tree looks > like an "Y". >   3. All **twigs** then grow vertical **stems** on their tip, length = 1. >   4. / The stems on **eastward** twigs lead to a **east/west** forking of > twigs. > > / The stems on **westward** twigs lead to a **north/south** forking of > twigs. > >   5. The growing iteration continues such that: > > / The stem on a **northward** twig grow like a **westward** twig. > > / The stem on a **southward** twig grow like a **eastward** twig. > > / Whenever two twigs converge at some location, a **fruit** is formed and no > further growing takes place. > > _**Q1: How many iterations does it take that >100 fruits are on the tree?_** _**Q2: What's the total length of stems and twigs at Q1's iteration?_** This **"EIORU tree"** , is equivalent to a square 2-D automata, and the rules are easily translated to automata rules (for conciseness I'll skip listing them :P) I wrote some Mathematica code to visualize such structure. The code works out, however is rather inefficient. If you find it interesting please advise me ways to efficientize it, thanks!               Clear[tree]; tree[vertical][0] = {{0, 0} -> "W"}; tree[vertical][n_] /; n>0 :=     tree[vertical][n] = (tree[diagonal][n] = Sort[tree[vertical][n - 1] /. rule1])     //. {p___, q_Rule, r___, s_Rule, t___} /; q[[1]] == s[[1]] :> {p, q[[1]] -> "Q", t}     (*iterate level by level. my method of removing Q=fruit from the next level is clumsy*)     rule1 = {     (*W*)({x_, y_} -> "W"):> Sequence[{x, y + 1} -> "W", {x, y - 1} -> "S"],     (*A*)({x_, y_} -> "A"):> Sequence[{x, y + 1} -> "W", {x, y - 1} -> "S"],     (*S*)({x_, y_} -> "S"):> Sequence[{x - 1, y} -> "A", {x + 1, y} -> "D"],     (*D*)({x_, y_} -> "D"):> Sequence[{x - 1, y} -> "A", {x + 1, y} -> "D"],     (*Q*)({_, _} -> "Q") -> Sequence[]};     (*I used rules to implement bifurcation*)     (*I used WASD in place of NWSE to make typing code easier. The resulting structure      may only differ in their chirality, but in spirit the same.*)          (*converting level i of tree - tree[i] into graphics*)     Clear[convert];     convert[i_]:= Join[{Hue[Mod[i, 10]/10]},      tree[diagonal][i] /. x:{_Integer, _} :> Append[x, 2 i - 1] /. rule2,     tree[vertical][i] /. x:{_Integer, _} :> Append[x, 2 i - 1] /. rule3]          (*rule2 is about diagonal lines representing twigs*)     rule2 = {     (*W*)({x_, y_, z_} -> "W") :> Line[{{x, y, z}, {x, y - 1, z - 1}}],     (*A*)({x_, y_, z_} -> "A") :> Line[{{x, y, z}, {x + 1, y, z - 1}}],     (*S*)({x_, y_, z_} -> "S") :> Line[{{x, y, z}, {x, y + 1, z - 1}}],     (*D*)({x_, y_, z_} -> "D") :> Line[{{x, y, z}, {x - 1, y, z - 1}}]};          (*rule3 is about stems and fruit*)     rule3 = {     (*Q*)({x_, y_, z_} -> "Q") :> {color = Black, PointSize[0.03], Point[{x, y, z}]},     (*stems*)({x_, y_, z_} -> Except["Q"]) :> Line[{{x, y, z}, {x, y, z + 1}}]};      It take about 5+ minutes to iterate up to 50 times. (pattern matching being potentially exponential time?!)               tree[vertical][50(**)]       Each level graphed separately               Table[Graphics3D[convert[i], ViewPoint -> Top, BoxStyle -> Dashed], {i, 1, 50(**)}]      Altogether a rather intricate structure               Graphics3D[Flatten@Table[convert[i], {i, 1, 50(**)}] /.      PointSize[_] -> PointSize[0], ViewPoint -> Top, BoxStyle -> Dashed]      Easy to enumerate fruits (or twigs, omitted here)               Accumulate@Table[Count[tree[vertical][i], "Q", Infinity], {i, 1, 50}]


title: List comprehension in Mathematica

text: Python supports a concept called "list comprehensions". Following is sample example               A=[[1,2,3], [2,3,4], [3,4,5]]     print( [ a + [i]  for a in A for i in range(1,4) if i in a] )      > >     [[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3], [2, 3, 4, 2], [2, 3, 4, 3], > [3, 4, 5, 3]] >   What's the most natural way to translate this _Python_ code to _Mathematica_? I have the following method:               A = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}};     Select[ Table[ a ~ Join ~ {i}, {a, A}, {i, 3}] ~ Flatten ~ 1, MemberQ[ Most @ #, Last @ #]&]      but I think it's neither fast nor elegant, therefore I am looking for a better way.


title: How do I select a random sample without replacement?

text: What is the module that selects a random sample of size k (without replacement) from a given population of size n, involving the command `Subsets`.


title: Why is Compile[] failing with message Compile::extscalar?

text: g = RandomGraph[{1000, 6000}];     NumberOfVertices = VertexCount @ g;     A = AdjacencyMatrix @ g;     ele = Flatten[A];     cnt = Length /@ A;     dsp = FoldList[Plus, 1, cnt];     fun = Compile[{{ele, _Integer, 1}, {cnt, _Integer, 1}, {dsp, _Integer,               1}, {n, _Integer}, {ccc, _Integer, 1}},             NestWhile[             Function[{cc},               Fold[Function[{c, v},                 ReplacePart[c,                  Module[{i,                    com = Complement[Range[n],                      c[[Take[ele, {dsp[[v]], dsp[[v]] + cnt[[v]] - 1}]]]]},                   RandomChoice[Append[com, c[[v]]]]], v]], cc,                RandomSample[Range[NumberOfVertices], NumberOfVertices]]], ccc,              Max[#] > n &]];      fun[ele, cnt, dsp, 100, Range[NumberOfVertices]]      Its giving me the following warnings:               Compile::extscalar: Function[{cc},Fold[Function[{c,v},ReplacePart[c,Module[{i,com=Complement[<<2>>]},RandomChoice[Append[com,Part[<<2>>]]]],v]],cc,RandomSample[Range[NumberOfVertices],NumberOfVertices]]] cannot be compiled and will be evaluated externally. The result is assumed to be of type Real. >>     Compile::extscalar: Max[#1]>n& cannot be compiled and will be evaluated externally. The result is assumed to be of type Real. >>


title: Applying a function to list of points and plot the results in ListPlot

text: Assume there are three groups of 2-dimensional coordinates               data = RandomVariate[NormalDistribution[#, .25], {15, 2}] & /@ Range[3];      Is there a way to `ListPlot` these data points just like               ListPlot[data, PlotStyle -> {Red, Blue, Green}]      ![](http://i.stack.imgur.com/CV9BD.png) but instead of the dots with the result of an integer-valued function, e.g. `Round[Norm[#]]&`, shown in the according colour? I already had a look at this and that question, but wasn't able to modify the answers to obtain the desired result.


title: Convert a list with three arguments {x0,x1, step} into an equidistant table?

text: How can I convert a list such as:               a = {1, 2, 0.1}      into sequence so that I can pass them into a function, e.g. I want to be able to do something like this               Range[a]      so that the output will be: > 1, 1.1, 1.2, ... , 2.0


title: How to examine the structure of Graphics objects

text: One difficulty I'm encountering in studying the structure of `Graphics` objects is that I have not yet found a way to print or display such structures that are sufficiently general. The `FullForm` of `Graphics` objects can be huge and extremely difficult to take in visually. I have tried to deal with this using `Shallow`, but with only limited success, because I find that "the interesting bits" in a `Graphics` not always occur at the same depth. It's a chicken-and-egg problem: to write a function that displays such structure in a useful way, I need to understand what such structure could be. But gaining this understanding is precisely what I'm trying to do here! In case it matters, I'm primarily interested in examining the structure of `Graphics` objects generated, directly or indirectly, by plotting commands such as `Plot`, `ListPlot`, etc.


title: Interpolating a ParametricFunction

text: Original domain of my independent variable `t` is 0 to 10 nanometers, but in _Mathematica_ (as in most numerical software), it's good idea to solve differential equation in the more 'usual' unit scale 0 to 10.               pfun = ParametricNDSolveValue[ {x''[           t] + a x'[t] + b^2 x[t] == 0, x[0] == 1,         x'[0] == 0}, x, {t, 0, 10}, {a,b}]      How can I scale back `t` in the resulting `ParametricFunction` to nanometers? Note: With `NDSolve` we used before version 9 (which introduced `ParametricNDSolveValue`), the result was an `InterpolatingFunction`, which was easily scaled back by using               Interpolation[{#*10^(-9), pfun[#]} & /@Range[0, 10, 10^(-1)]]


title: How to remove scroll bars from embedded cdf?

text: I am using the deploy command to embed a CDF file in an HTML page. I am using the annoying but currently necessary `fullscreen:'true'` trick to reveal the "Enable Dynamics" button. Regardless of what size arguments I use in the cdf.embed function, I get an unnecessary vertical scroll bar in the result rendered in the web page. How can I get rid of this? Are there other undocumented arguments to cdf.embed?


title: After modifying expression, new result doesn't replace old one

text: After I modify and re-evaluate an expression, the new result doesn't replace the old one. Rather, what happens is that the old result gets pushed down and _Mathematica_ displays the current result at the top. It looks like this:               In[20] := (* expression *)     Out[20] = (* result *)     Out[19] = (* older result, when In[20] was In[19] *)     Out[18] = ...     ...etc      I'm pretty sure I messed up my preferences, but I can't revert to defaults, because I have another issure resolved (after trying for some time) and not sure exactly how I did it. Following old > If It Works, Don't Fix It So I'm reluctant to restore the default settings, the other (fixed) issue being far more important to me. ( _Mathematica_ 9 on Ubuntu 12)


title: how to select all cells with specific property such as the ones that are closed

text: I have to close many cells each time before I export a notebook to HTML since I do not want to display many code cells and other cells. I select each cell one by one, and do `cell->cell properties->open` to uncheck it, so it closes. Then I export to html. Then I have to go reverse the whole process one by one again. I do this many times during the day. I am getting tired of doing this. I know in V9 there is now a cell API so I am sure there is a way to program this where one will add each cell into some cell group, and then issue a command to open or close all cells. But, is there a way, from the notebook UI, a way to say to Mathematica: please select all closed cells. Then when they are selected, I can go use the UI to change the property of all selected cells at once using the cell->... as above. (I still have to select the cells again one by one when I want to close them again, but at least I can reduce the amount of work by half). Actually, ideally what I'd like to do, is say: Export all cells except the `Input` and `Code` cells. i.e. selective `Export` by types of cells. That will be the most flexible way. i.e. there should be an export wizard, where one can select type of cells to export. So one can check in/off classes of cells in notebook, then click export. Default will be to export all cells. thank you


title: exporting list of matrices in mathematica

text: I am working on some problem which requires generating a list of random matrices. So I used the code (actually a shortened version of the code, but it does not matter)               L={};     For[n = 1, n <= 10, n++,      R = RandomComplex[{-1 - 1 I, 1 + 1 I}, {2,2}];     ApppendTo[L,R]     ]     Export["list.dat",L]      So far so good, but when I try to import them by               Import["list.dat"]      it imports the list but pus a ',' after each and every string. In particular, after each +, -, I, }, and after each ',' as well! Some variations (like importing as table and so on) are not giving anything better. I tried to export it as .mat format which gives the following error               Export::type: {{{-0.0542175+0.284324 I,-<<21>>-<<19>> I},{<<1>>}},<<9>>} cannot be exported to the MAT format. >>      I am using mathematica 6 and 7 both. Advanced thanks for any hint/ suggestions.


title: How to export data to specific rows and columns in XL file from Mathematica?

text: I have an `XL` File with data like :                 {{1,2,3},{4,5,6},{7,8,9}}      That `XL` file name as "MySheet1". I want to   1. change {2,2} position value(5 to 11).   2. change entire Third row. for that purpose I tryed with `Export` still not get it. can anybody help me?


title: Structure of Graphics (esp. those produced by Plot, ListPlot, etc.)

text: I'm looking for a description of the _structure_ of `Graphics` objects, _aimed at the advanced_ Mathematica _programmer_. * * * The motivation for this question is the following. I have several `Module`-type functions that, as part of their operation, have to manipulate `Graphics` objects (primarily those generated by plotting commands). I find that these functions often produce undesired results, and the reason is, invariably, that the function has assumed something about the structure of `Graphics` objects that turns out not to hold in general. Hence, I want to learn more about the internal structure of the `Graphics` objects generated by `Plot`, `ListPlot`, and friends. Unfortunately, I cannot distill my overall state of confusion into one or two concrete questions. I have a ton of questions, but from my ignorant vantage point, I cannot rank these questions in order of importance. Here's an example out of many I could give: "why do the lists of "primitives" in so many of the `Graphics` objects that I produce with plotting commands begin and end with empty lists?" For all I know, the answer to this question could just as easily be hugely illuminating, or be utterly banal, or, worse yet, may give rise to further questions. * * * I've read the documentation for `Graphics` and the tutorial _The Structure of Graphics_ (which, despite the promising-sounding title, did not shed as much light as I'd hoped). (I've also watched the Graphics Language Quick Start, which is generally instructive, but, as its name suggests, far more high-level and beginner-oriented than what I'm looking for.)


title: I got wrong answers when solving an equation

text: I have this expression:                eqn= -(P (d4^6 + d4^4 (-2 d5^2 +          3 (l - z)^2) +                 d4^2 (d5^4 - 2 d5^2 (l - z)^2 + 3 (l - z)^4) +                 2 d4 d5^2 Sqrt[-(-d4^2+ (d3-d5)^2 -(l-z)^2) (-d4^2 + (d3 + d5)^2 - (l - z)^2)] (-l + z) +                 d3^4 (d4 + l - z) (d4 - l + z) -                 (d5^2 + (l - z)^2) (l - z)^2 (d5 + l - z) (d5 - l + z) -                 2 d3^2 (d4^4 + d4^2 (d5^2 + (l - z)^2) - d5^2 (l - z)^2 +                 d4 Sqrt[-(-d4^2 + (d3 - d5)^2 - (l - z)^2) (-d4^2 + (d3 + d5)^2 - (l - z)^2)] (-l + z))));      when I tried to solve:                  Solve[eqn == 0, z];        I got the following results:               {{z -> I (d4 - I l)},       {z -> -I (d4 + I l)},       {z -> -Sqrt[d3^2 - d4^2 - 2 d4 d5 - d5^2] + l},       {z ->  Sqrt[d3^2 - d4^2 - 2 d4 d5 - d5^2] + l},       {z -> -Sqrt[d3^2 - d4^2 + 2 d4 d5 - d5^2] + l},       {z ->  Sqrt[d3^2 - d4^2 + 2 d4 d5 - d5^2] + l},       {z -> -Sqrt[-d3^2 - 2 d3 d4 - d4^2 + d5^2] + l},       {z ->  Sqrt[-d3^2 - 2 d3 d4 - d4^2 + d5^2] + l},       {z -> -Sqrt[-d3^2 + 2 d3 d4 - d4^2 + d5^2] + l},      {z ->  Sqrt[-d3^2 + 2 d3 d4 - d4^2 + d5^2] + l}}      But when I wanted to check the previous results, some of them wasn't correct, like this one:               FullSimplify[ eqn /. {z -> Sqrt[d3^2 - d4^2 - 2 d4 d5 - d5^2] + l},                            Assumptions -> d3 > 0 && d5 > 0]     (*      -8 d4 (d3 - d5) d5 (d3 + d5) (-d3^2 + (d4 + d5)^2) P     *)      Any help with this ?


title: How to create bounded diagram plot?

text: I have set of points:               pts={{1.25, 9.75}, {2.5, 9.75}, {2.5, 9.25}, {4, 9.7}, {4, 9.2}, {4,        8.75}, {4, 8.25}, {5.5, 9.7}, {5.5, 9.1}, {5.5, 8.5}, {5.5,        8.0}, {5.5, 7.5}, {7, 9.8}, {7, 9.2}, {7, 8.75}, {7, 8.1}, {7,        7.6}, {9, 9.6}, {9, 9.1}, {9, 8.75}, {9, 8.2}, {9, 7.75}, {11,        9.8}, {11, 9.2}, {11, 8.75}, {13, 9.25}, {13, 9.72}};     ListPlot[pts]      and a bounding line:               x = {0, 2.5, 5, 10, 15};     y = {10, 8.27, 7, 7.5, 10};     b=Transpose[{x,y}];     ListLinePlot[b]      How to create a bounded diagram plot? When I use:               Needs["ComputationalGeometry`"]     BoundedDiagram[b, pts]      I get a lot of errors like:               Part::partw: Part 1 of {} does not exist. >>     Part::partw: Part 1 of {} does not exist. >>     Part::pspec: Part specification {}[[1,2]] is neither a machine-sized integer nor a list of machine-sized integers. >>     Part::pspec: Part specification {}[[1,2]] is neither a machine-sized integer nor a list of machine-sized integers. >>      Which don't really let me understand why it doesn't work. Voronoi diagram, convex hull or delaunay triangulation works just perfect on these points.


title: Is there an easy way to divide a matrix into four blocks?

text: I often get a data table with column names and row names. For example:               Gene_Name   ID         CHR   Sample_1    Sample_2    Sample_3   ...     Itm2a       NM_00134   chrX  0.00        1.23        2.45       ...     Fam109a     NM_02342   chr7  1.44        4.44        2.14       ...     ...         ...        ...   ...         ...         ...        ...      I'd like to divide it into 4 blocks, namely the data block (with all the numeric data reads), column names, row names and corner names. Currently I usually do something like this:               rw = Import["table.csv"];     colnames = rw[[1 ;; 1, 4 ;;]];     rownames = rw[[2 ;;, 1 ;; 3]];     cornernames = rw[[1 ;; 1, 1 ;; 3]];     data = rw[[2 ;;, 4 ;;]];      which is quite clumsy and feels not "mathmatica". Can anyone do better?