Markov Chain for combined events?

I was wondering how to apply Markov steady-state chains to a simple case in genetics, eye colour. Assuming the probabilities of being brown, green or blue eyed, given your parents were a certain colour combination are:               Br + Br - Br 75%  , Gr 18.75% , Bl 6.25%     Gr + Br - Br 50%  , Gr 37.5%  , Bl 12.5%     Bl + Br - Br 50%  , Gr 0%     , Bl 50%     Gr + Gr - Br 0.5% , Gr 74.75% , Bl 24.75%     Gr + Bl - Br 0%   , Gr 50%    , Bl 50%     Bl + Bl - Br 0%   , Gr 1%     , Bl 99%      Corresponding matrix:               {{3/4, 1/2, 1/2, 0.005, 0, 0}, {0.1875, 0.375, 0, 0.7475, 1/2, 1/       100}, {0.0625, 0.125, 1/2, 0.2475, 1/2, 99/100}}      I want to find the steady state for the eye colour of the population.


How do I plot a plane EM wave?

I would like to display an electromagnetic (EM) wave. I have written code that works, but it does not "shade" the area between the graph and the axes. Both the `Filling` and `EdgeForm` commands are ignored.               strength = 2; frequency = 3;          wave1 = ParametricPlot3D[{t (x/6.28), -strength Sin[frequency t (x/6.28)], 0},        {t, 0, 2 Pi},        PlotStyle->Directive[Thickness[.007], Lighter[Red, .5], Filling -> Axis]];     wave2 = ParametricPlot3D[{t (x/6.28), 0, strength Sin[frequency t(x/6.28)]},        {t, 0, 2 Pi},        PlotStyle -> Directive[Thickness[.007], Lighter[Blue, .5], Filling -> Axis]];          Show[wave1, wave2, Graphics3D[EdgeForm[Pink], wave1],       Graphics3D[EdgeForm[LightBlue], wave2],        Axes->False, Boxed->False, PlotRange->All, ImageSize->{500, 400}]      I would like to accomplish filling the portion between the two sinusoidal waves and the direction of propagation of the wave with color.


ArcTan and Compile

See following three snippet code:               (*can compile*)     range = Range[-2, 2, 0.005];     Compile[{},        With[{r = range}, Table[ArcTan[x, y], {x, r}, {y, r}]]][];          (*can compile*)     Compile[{},         With[{r = Range[-2, 2, 0.005 - 10^-8]}, Table[ArcTan[x, y], {x, r}, {y, r}]]][];          (*can't compile*)     Compile[{},        With[{r = Range[-2, 2, 0.005]}, Table[ArcTan[x, y], {x, r}, {y, r}]]][];      Why the last code can't be compiled? I used Mathematica 9.0.1.


How do I calculate the area of a polygon given its coordinates?

I have a polygon:               Polygon[{{0, 200 }, {200, 100}, {500, 300}, {100, 700}}]      How can I figure out its area? The docs page does not have any example. So far I've reached this point with no success:               Needs["Polytopes`"]     Area[Polygon[{{0, 200 }, {200, 100}, {500, 300}, {100, 700}}]];      Concerning `Area`, the documentation states: > Area[polygon]   >  $\ \ \ \ \ $ gives the area of polygon polygon, when the edges of polygon > have unit length. So it is possible that my question really should be **how to set unit length on edges of polygon?**


Modelling the effect of a structure on a "tsunami" (hyperbolic wave equation)

So, the hyperbolic wave equation can be quite easily solved in _Mathematica_ like this:               L = 5;     TMax = 10;     tsunamiEqn = u /. NDSolve[{\!\(     \*SubscriptBox[\(\[PartialD]\), \(t, t\)]\(u[t, x, y]\)\) == \!\(     \*SubscriptBox[\(\[PartialD]\), \(x, x\)]\(u[t, x, y]\)\) + \!\(     \*SubscriptBox[\(\[PartialD]\), \(y, y\)]\(u[t, x, y]\)\),            u[0, x, y] == 0.15 E^-(x^2 + y^2),           \!\(\*SuperscriptBox[\(u\),      TagBox[     RowBox[{"(",      RowBox[{"1", ",", "0", ",", "0"}], ")"}],     Derivative],     MultilineFunction->None]\)[0, x, y] == 0, u[t, -L, y] == u[t, L, y],            u[t, x, -L] == u[t, x, L]},             u, {t, 0, TMax}, {x, -L, L}, {y, -L, L}][[1]];      One can then plot it or `Manipulate` it via the following snippet:               Manipulate[      Plot3D[       tsunamiEqn[fac TMax, x, y], {x, -L, L}, {y, -L, L},       PlotRange -> {{-L, L}, {-L, L}, {-0.1, 0.2}},       Mesh -> 10,       PlotStyle -> {LightBlue, Specularity[White, 50]}       ],      {fac, 0, 0.9}      ]      **Now my question is** : How do I include a structure inside this "pond". I would like to see what happens when the wave interacts with a square block or so. I am drawing a blank right now as to how I would want to include that: A boundary condition? (would seem a little complex) **Here are a few snapshots of this wave travelling:** ![Time=0](http://i.stack.imgur.com/CYK0m.jpg) ![Time=0.2 TMax](http://i.stack.imgur.com/iIt48.jpg) ![Time=0.3 TMax](http://i.stack.imgur.com/mD6wt.jpg)


Complex surface: Finding the perimeter of the union of multiple disc intersections

Consider a system of $N$ circles($N>40$) Each of radius $5$ and the center of these circles along a circle at origin of radius $3$ [as given in code]. Code for above description :-               Graphics[Table[{Hue[t/40],         Circle[{3 Sin[2 Pi (t - 1)/40], 3 Cos[2 Pi (t - 1)/40]}, 5]}, {t,         40}]]      I want to find the perimeter of the resultant figure formed by regions covered by the union of the "intersection of any two arbitrary circles". Then, the perimeter of the resultant figure formed by regions covered by the union of the"intersection of any three arbitrary circles". And so on till we intersect of all the circles.


HoldForm[Operator ##] on some list

Recently in response to this question Mr.Wizard suggested an unusual way to summing numbers. This doesn't seem to be documented.               HoldForm[+##] & @@ RandomInteger[100, 2]      This works fine for `Plus` and in case of `-` it generates -ive of product of list elements. I could not find out how to write a close variation of this for `Divide` or `Subtract` or other operations. Can someone please shed some light on this ?


Plot CPU time vs iteration?

I would like to generate a plot of CPU time vs number of iterations. For example, if I were to calculate the solution of a system of differential equations in state-space form using the summation of e^(A t) (or any series expansion for that matter):               A = {{1, 2}, {3, 4}}     sol=Sum[(MatrixPower[A, j] t^j)  /j!, {j, 0, 200}]      I tried:               Table[Timing[N[Sum[(MatrixPower[A, j] t^j)  /j!, {j, 0, i}]]], {i, 0,        200}]      but this outputs the solution of the summation along with the time. I only require the cpu time for each individual iteration and the iteration number. Can someone point me in the right direction here?


Dealing with square roots

Consider following expression: $$ \sqrt{-\left(2 \sqrt{x^{-8/3}-x^{-4/3}+1}\, x^{4/3}+5\right) x^{4/3}+4 \sqrt{x^{-8/3}-x^{-4/3}+1}\, x^{4/3}+2 x^{8/3}+5} $$ In code:               f[x_] := Sqrt[        -(2 Sqrt[x^(-8/3) - x^(-4/3) + 1] x^(4/3) + 5) x^(4/3)        + 4 Sqrt[x^(-8/3) - x^(-4/3) + 1] x^(4/3) + 2 x^(8/3) + 5     ]      Why in Mathematica one can see non smoothness at $x\sim10^4$?               Plot[f[x], {x, 0, 10^4}]      ![Mathematica graphics](http://i.stack.imgur.com/zFdTw.png) I guess, it is a numerical issue, but then how one can deal with it?


How to increase precision: $MinPrecision does not help

I have the following series:               f[x_] := Sin[x]     n := 50          Ni3[x_] := Sum[(f[k]*(-1)^k)/((x - k)*Gamma[k + 1]*Gamma[n - k + 1]), {k, 0, n}]/                Sum[(-1)^k/((x - k)*Gamma[k + 1]*Gamma[n - k + 1]), {k, 0, n}]          Plot[{Ni3[x], f[x]}, {x, -7, 7}, AspectRatio -> Automatic, PlotRange -> 10]      At number of terms n below 40 the plot gives what is expected. But when increasing it above 50 the plot becomes corrupted. The setting `$MinPrecision` does not affect the result. The series is proven to converge to $f(x)=\sin(x)$. ![bad plot](http://i.stack.imgur.com/ojzck.png)


Relative error plot

I was plotting the relative error of the $e^{11/12 -n}n^{n+1/2}$ approximation to $n!$ as $n$ gets larger and larger, and at some very large value of $n$ _Mathematica_ gives this plot: ![enter image description here](http://i.stack.imgur.com/Q8eFU.png) Can somebody explain what exactly the plot means? Of course, I understand that, for larger and larger $n$, the relative error tends to a limit, but I am not sure how to interpret this plot. In particular, I don't understand how the error can show greater variation as $n$ grows large. Thanks. Edit: I want to add that when $n$ is an order of magnitude less what I get is something like this: ![http://i.stack.imgur.com/5zK7i.png](http://i.stack.imgur.com/BjD6o.png)


Strange behavior when replacing variables by numerical values

I have a rather complicated function with parameters {a, b, c, d, e, f, k}, and I'd like to know its behavior as a function of k alone given other parameters, so I try the following code:               myFunction = D[ComplexExpand[Arg[((a^2 - 2 (2 k + I e - 2 c) (k + d - c))^2/((a^2 - 2 (2 k + I (b + e + 2 I c)) (k + d - c))^2 + 4 E^(2 I k f) b^2 (k + d - c)^2))], TargetFunctions -> {Re, Im}] // Simplify, k];     myFunctionWithValues[k_] := Evaluate[myFunction /. {b -> 10, a -> 2, c -> 100, d -> 0, e -> 1, f -> Pi/100} // FullSimplify]     LogPlot[myFunctionWithValues[k], {k, 95, 105}, PlotRange -> All]      > ![enter image description here](http://i.stack.imgur.com/nay9y.png) and the outcome looks very bizarre. It can't be correct. To comfirm this, for example, I look at the value of `myFunctionWithValues` at the center `k=100` by 1) directly replacing k by 100 and 2) by taking the limit k->100, and they disagree with each other:               myFunctionWithValues[k] /. k -> 100 // N      > 315120.               Limit[myFunctionWithValues[k], k -> 100] // N      > 10. Apparently the latter gives a more reasonable result (which is checked by other approaches). Moreover, if I replace the value of all parameters (including k) in the very beginning, _Mathematica_ also yields the same result:               myFunction /. {b -> 10, a -> 2, k -> c, d -> 0, e -> 1, f -> Pi/100} // Simplify      > 10               myFunction /. {b -> 10, a -> 2, c -> 100, d -> 0, e -> 1, f -> Pi/100, k -> 100} // N      > 10. And the correct plot can be given by the following two ways:               (Limit[myFunctionWithValues[k], k -> #]) & /@ Range[95, 105, 1/10] //N;     ListPlot[%, PlotRange -> All, Joined -> True, AxesOrigin -> {100, 0}, DataRange -> {95, 105}, PlotMarkers -> Automatic]      > ![enter image description here](http://i.stack.imgur.com/FQDo5.png)               Plot[myFunction /. {b -> 10, a -> 2, c -> 100, d -> 0, e -> 1, f -> Pi/100}, {k, 95, 105}, PlotRange -> All, AxesOrigin -> {100, 0}]      > ![enter image description here](http://i.stack.imgur.com/Oi7bt.png) _**Question:_** What's going on here? Why can't I simply plot `myFunctionWithValues` but have to take the limit of k at each point? More precisely, what's the difference between using the replacement rules and taking limits? I thought it should be the same given that in my case there's no singularity causing trouble, otherwise _Mathematica_ would give me an error message.


Numerical instability in cosh and sinh - integral functions

I'm trying to calculate the function:               CoshIntegral[x] Sinh[x] - Cosh[x] SinhIntegral[x]      Unfortunately _Mathematica_ seems to hit a point (x~20) and things become unstable (see plot below), there shouldn't be any infinities in the area, so I am rather confused as to what is going on! ![plot of above function](http://i.stack.imgur.com/axuW0.jpg) Does anyone know why this is happening and how to fix it?


ReplaceAll[] and Limit[] don't give correct results for this expression under extreme variables

> **Possible Duplicate:**   >  Funny behaviour when plotting a polynomial of high degree and large > coefficients               1/x^2 + (3 + x)/(6 (1 - Exp[x] + x))      ——This is a expression that seems nothing special, so does its limit when `x->0`:               Limit[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)), x -> 0]     (* => 1/12 *)      But it becomes strange when trying to calculate a _x_ near zero,               1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)) /. x -> 0.00001     (* => -19403.7 *)     1/0.00001^2 + (3 + 0.00001)/(6 (1 - Exp[0.00001] + 0.00001))     (* => -19403.7 *)     Limit[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)), x -> 0.00001]     (* => 0. *)      Many people (including me) may check the curve of the expression as the first reaction for these results:               Plot[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)), {x, 0, 0.00001}]      And see: ![A curve under low precision](http://i.stack.imgur.com/Cecdg.jpg) Aha, it explains the matter! The curve is actually oscillating near zero!… but wait, try this:               Plot[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)), {x, 0, 0.001}, WorkingPrecision -> 30]      Now we see: ![A curve under high presision](http://i.stack.imgur.com/rRVc7.jpg) * * * So all of these turn out to be a story about precision once again (why I always encounter this! ). I also found some resource for this error:               Series[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)), {x, 0, 10}];     Normal[%] /. x -> 0.00001     (* => 0.0833332 *)          N[1/x^2 + (3 + x)/(6 (1 - Exp[x] + x)) /. x -> 10^-5, 6]     (* => 0.0833332 *)      But, can this problem be solved only with `ReplaceAll` and `Limit`? Also, we see that Mma doesn't give warnings for these great error (while this sort of thing frequently occurs when I use `NDSolve` though the error seems not that big…it's another story), any way to make Mma give a warning message or something?


Hypergeometric function with large parameters

I need an efficient and accurate method to evaluate hypergeometric ratios of the form: $$\frac{_{2}F_{1}(a+1,b;c;x)}{_{2}F_{1}(a,b;c;x)}$$ for large positive values of `a,b,c`. However, if you plot:               Plot[Hypergeometric2F1Regularized[601, Rationalize[100.1], 100, x]/       Hypergeometric2F1Regularized[600, Rationalize[100.1], 100, x],        {x, 0, 1}]      you will see that these ratios can be inaccurate in Mathematica. What can I do?


Wolfram workbench syntax highlighting for local variables inside compile

Lately I've been working quite a lot with `Compile`. I also started using Wolfram Workbench. So a natural question arises: Is it possible to have syntax highlighting for local variable variables inside compile as well? Here is a screenshot demonstrating the problem. Notice the blue `x`'s in the lower right hand side of the image? These should be green. ![Screenshot](http://i.stack.imgur.com/US15o.png) I didn't manage to find anything under the preferences. I'm using WB 2.0


RegionPlot3D contour problem

I have a little problem and didn't succeed trying to solve it on my own. Situation is, I need a visualization of the function $s - 3\cdot s\cdot q + q$ as a region on p == 0 if function's value is less than zero, a region on p == 1 if the function > 0, and a contour if the function equals to zero. What I've done:               RegionPlot3D[(s - 3q*s + q > 0 && p == 0) || (s - 3q*s + q <= 0  && p == 1),                            {q, 0, 1}, {s, 0, 1}, {p, 0, 1}, AxesLabel -> Automatic]      which give me this: ![](http://i.stack.imgur.com/awV5u.png) but what I need to add is a contour $s - 3\cdot s\cdot q + q = 0$ to this plot, but also remain able to intersect this set with others. The contour is simple:               ContourPlot3D[s - 3 q*s + q == 0, {p, 0, 1}, {q, 0, 1}, {s, 0, 1}]      ![](http://i.stack.imgur.com/UZqCS.png) I've tried to use a little hint with inequality range               RegionPlot3D[(s - 3 q s + q > 0 && p == 0) || (s - 3 q s + q <= 0 &&      p == 1) || Abs[s - 3 q s + q] < 0.01, {q, 0, 1}, {s, 0, 1}, {p,      0, 1}, AxesLabel -> Automatic, PlotPoint -> 100]      This is sufficiently accurate, but produces a 3d set, instead of a surface. Any ideas how to reach my goal? P.S. the best would be a solution to such kind of problems in general, because, sometimes the contour equation can be not that simple.


How can I improve my Zooming code?

I recently started to work with the `EventHandler` function to make it possible to Zoom, Pan, etc, with only the use of a mouse. I have found a way to zoom that is somewhat working without a keyboard, but was wondering if anyone had any tips to improve it. It works very slowly, often asking me if I'd like to disable dynamic updating. Obviously, this is unacceptable for any practical purpose. The code so far is as follows:               EventHandler[     Dynamic[Graphics3D[Cylinder[], ViewAngle -> Dynamic[viewval]],      Initialization :> (mousecoord1 = {0, 0}; mousecoord2 = {0, 0};      size = {0, 0}; fracmag = 0; difference = 0; anglediff = 0;      viewval = 7*Pi/36)], {"MouseDown" :> (mousecoord1 =       CurrentValue[MousePosition];      size = CurrentValue[       ImageSize])}, {"MouseDragged" :> (mousecoord2 =       CurrentValue[MousePosition];      difference = mousecoord2 - mousecoord1;      fracmag = Norm[difference]/Norm[size];      anglediff = fracmag*(Pi - viewval);      Which[difference[[2]] < 0,       Min[viewval = viewval + anglediff, Pi - 0.00001],       difference[[2]] > 0, Max[viewval = viewval - anglediff, 0.00001],       difference[[2]] = 0,       viewval = viewval])}, {"MouseUp" :> (anglediff = 0;      difference = {0, 0}; mousecoord1 = {0, 0}; mousecoord2 = {0, 0})}]      The code above uses a simple 3d Graphic, a cylinder, and the `ViewAngle` option to track a mouse click and drag which then uses the ratio between the drag and the image size to determine how much to zoom in or out.


how to open Hyperlinked files by default software?

Non- _Mathematica_ formats, e.g. .doc or .txt files, are directly shown in a new notebook when I click on a hyperlink pointing at these objects. But I would rather have (for example) .doc files opened using Microsoft Word. How can one create a hyperlink that opens a file in its associated application, rather than in _Mathematica_?


Should I end all definitions from packages with semicolon?

I noticed that if I open a `.m` file in Mathematica and click on the `Run Package` button, all the `Set` definitions will be printed as output if they are not ended in `;`. The same for `function::usage` definitions. This is probably harmless, but I am wondering if there is a guidance on weather semicolons should be appended at the end of `Set` or `SetDelayed` definitions. Looking into the Mathematica libraries source code, I can see both approaches - some `Module` functions have `;` at the end, others do not.


How do I export matrices into matlab format?

For example:               M={};      For[n = 0, n < 100, n = n + 1,       ... ...         M=Append[M, Resultmatrix ];       (*Resultmatrix is the intermediate reslut 4X4 matrix*)     ]     Export["data.mat", M]      But when loading data.mat in Matlab, I find that M splits into multiple variables with names like Expression1, Expression2, Expression3 .... I also tried XLS format, but each 4x4 matrix in the list of matrices appears in an individual worksheet. So my question is how can I put M in a single variable, thus I could manipulate it.


Why rule does not work if Flat attribute?

The following works:               In[39]:= ClearAttributes[M, Flat];     Replace[M[F1[a]], M[x_F1] | M[x_F2] -> x]     Replace[M[F2[a]], M[x_F1] | M[x_F2] -> x]     Replace[M[F3[a]], M[x_F1] | M[x_F2] -> x]          Out[40]= F1[a]          Out[41]= F2[a]          Out[42]= M[F3[a]]      the following does not               In[34]:= ClearAttributes[M, Flat];     SetAttributes[M, {Flat}];     Replace[M[F1[a]], M[x_F1] | M[x_F2] -> x]     Replace[M[F2[a]], M[x_F1] | M[x_F2] -> x]     Replace[M[F3[a]], M[x_F1] | M[x_F2] -> x]          Out[36]= M[F1[a]]          Out[37]= M[F2[a]]          Out[38]= M[F3[a]]      why?


Why Do I Have Large Error Margin Using NonLinearModelFit function

# Data {2.5984*10^-56,1.2266*10^-25,2.77402*10^-19,1.14182*10^-15,3.43647*10^-13,2.46313*10^-11,7.13917*10^-10,1.11045*10^-8,1.09754*10^-7,7.68589*10^-7,4.10723*10^-6,0.0000176576,0.0000634956,0.000196694,0.000537035,0.00131592,0.00293618,0.00603686,0.0115497,0.0207306,0.035151,0.0566368,0.0871538,0.128646,0.18284,0.25105,0.333986,0.43162,0.543096,0.666724,0.800034,0.939904,1.08273,1.22464,1.36169,1.49013,1.60652,1.70795,1.79211,1.85739,1.90287,1.92831,1.93411,1.92122,1.89103,1.84532,1.78606,1.71543,1.6356,1.54874,1.45694,1.36212,1.26602,1.17018,1.07592,0.984329,0.896293,0.812488,0.733406,0.659374,0.590571,0.527055,0.468779,0.415615,0.36737,0.323804,0.284642,0.249587,0.218334,0.190572,0.165997,0.144312,0.125236,0.1085,0.0938559,0.0810734,0.0699408,0.0602653,0.0518725,0.0446053,0.038323,0.0329003,0.0282261,0.0242021,0.0207417,0.0177691,0.0152178,0.0130299,0.0111549,0.0095491,0.00817446,0.00699822,0.00599209,0.00513167,0.00439598,0.003767,0.00322925,0.00276948,0.00237632,0.00204006} I'm having a little problem with the NonLinearModelFit function. I'm hoping someone can point me in the right direction please. I have this data points: https://www.dropbox.com/s/5hflg2nvko26hpz/question.nb When I plot the data points I have this: ![datapoints](http://i.stack.imgur.com/MjZH5.png) Then I use a Rice (Rician) Distribution Curve as model for fitting. For this, I used $$\frac{x \exp \left(-\frac{v^2+x^2}{2 \sigma ^2}\right) I_0\left(\frac{x v}{\sigma ^2}\right)}{\sigma ^2}$$ But when I plot both curves together I get something like this figure where the fit is the very tiny one below: ![enter image description here](http://i.stack.imgur.com/5t9Iz.png) I checked the Residual fit and I got something really disturbing. Showing that my fit has a large error margin: ![enter image description here](http://i.stack.imgur.com/gSZN3.png) Honestly, I'm not sure what's wrong. I've spent some time on this and I think I need an outside eye to help look at it. Any idea will be much appreciated. Thanks friends.


Solving Differential Equation depending on variables solved by NDSolve

How to solve a differential equation which consists of variables depending upon another differential equation?


Want to use column names as indices, but without quotes

The following works:               devFactors =SQLExecute[SicsDBconnection, "SELECT * FROM " <>  devFactorTable];     devFactors[[1]]          colNames = {ALOB, Country, Months, LossFactor, EarnedFactor};     asRules = Rule @@@ Transpose[{colNames, Range[Length@colNames]}];     newList[col_] := devFactors[[All, col /. asRules]];     newList[LossFactor][[1]]      and produces:               {"Property Treaty PR", "Morristown", 12, 3.5736, 3.09256}     3.5736      I would like to pull those column names from SQL as the following:               colNames = SQLColumnNames[SicsDBconnection, SQLTable[devFactorTable]][[All, 2]];      But, when I do this, colNames now is a list of strings instead of a list of symbols and I have to reference my devFactors list like:               newList["LossFactor"][[1]]      I would like to be able to reference it using the symbol LossFactor instead of the string. I see that I can't replace the head of an atom, so I think that means that I can't turn those strings from SQL into symbols. Obviously this isn't a critical problem, but does anyone know how I can accomplish this, or if it's possible?


Using MaxStepFraction as ticks on plot

Is there any way I could use the `MaxStepFraction` (or grid size) as used in `NDSolve` in the example below as ticks on the 3d Plot? That was I would be able to plot the grid points on the X and Y axis. I tried creating a table and using that as the argument in `Ticks` but that didn't work. Minimum working example:               Clear[u, L, t, x, y, sol, Eq]     L = 4;     Eq = -D[u[t, x, y], t, t] + D[u[t, x, y], x, x] +         D[u[t, x, y], y, y] + Sin[u[t, x, y]];     uSol = u /. NDSolve[{          Eq == 0, u[t, -L, y] == u[t, L, y],           u[t, x, -L] == u[t, x, L],           u[0, x, y] == Exp[-(x^2 + y^2)],           Derivative[1, 0, 0][u][0, x, y] == 0          },          u,          {t, 0, L/2}, {x, -L, L}, {y, -L, L},         MaxStepFraction -> 1/11         ][[1]]                         tt = 1.2;     Plot3D[ uSol[tt, x, y], {x, 0, L}, {y, 0, L},       Ticks -> {{0, 2/5, 4/5, 6/5, 8/5, 2, 12/5, 14/5, 16/5, 18/5, 4}, {0,          2/5, 4/5, 6/5, 8/5, 2, 12/5, 14/5, 16/5, 18/5, 4}}]      ![enter image description here](http://i.stack.imgur.com/CEJe0.png) The ticks in the above figure were created using, `Table[i 4/10, {i, 10}]` and then manually pasted into the curly brackets. Obviously, that isn't the most efficient way. I tried pasting the `Table` command inside `Plot3D` but that didn't work.


Strange behavior of undocumented RawArray and ArrayObject expressions

I discovered several strange results and inconsistencies while trying to understand what undocumented `RawArray` and `ArrayObject` really are:               image = ImageResize[Import["http://wolfram.com/favicon.ico"][[1]], 1];          rawArray = ToBoxes[image][[1, 1, 1]]     (* RawArray[Byte, <1,1,4>] *)          rawArray // Head     (* RawArray *)          rawArray // Length     (* 2 *)          rawArray // InputForm     (* RawArray["Byte", {{{237, 153, 142, 255}}}] *)          Hold[RawArray]["Byte", {{{237, 153, 142, 255}}}] // Depth     (* 5 *)          rawArray // Depth     (* 2 *)          rawArray[[0]]     (* Part::partd: Part specification RawArray[Byte,<1,1,4>][[0]] is longer than depth of object. >> *)     (* RawArray *)          rawArray[[1]]     (* Part::partd: Part specification RawArray[Byte,<1,1,4>][[1]] is longer than depth of object. >> *)     (* "Byte" *)          arrayObject = rawArray[[2]]     (* Part::partd: Part specification RawArray[Byte,<1,1,4>][[2]] is longer than depth of object. >> *)     (* ArrayObject[Byte, <4>] *)          arrayObject // Head     (* Language`ArrayObject *)          arrayObject // AtomQ     (* True *)          wdx = ExportString[arrayObject, "WDX"];          ImportString[wdx, "WDX"]     (* {{{237, 153, 142, 255}}} *)          % // Head     (* List *)          Uncompress[Compress[arrayObject]]     (* {{{237, 153, 142, 255}}} *)          arrayObject // FullForm     (* List[List[List[237, 153, 142, 255]]] *)          arrayObject // InputForm     (* Raw[Language`ArrayObject, "78c4801b00000000"] *)          inputFormStr = ToString[arrayObject, InputForm]     (* "Raw[Language`ArrayObject, \"78c4801b00000000\"]" *)          heldArrayObject = ToExpression[inputFormStr, InputForm, Hold]     (* Hold[Raw[Language`ArrayObject, "78c4801b00000000"]] *)          heldArrayObject[[1, 0]]     (* Raw *)          heldArrayObject[[1, 1]]     (* Language`ArrayObject *)          heldArrayObject[[1, 2]]     (* "78c4801b00000000" *)          arrayObject2 = ReleaseHold[heldArrayObject]     (* 0 *)          arrayObject2 == 0     (* 0 == 0 *)          % // FullForm     (* Equal[1, 0] *)          ToBoxes[arrayObject2]     (* 0 *)          % // Head     (* Integer *)          arrayObject2 // Head     (* Language`ArrayObject *)          arrayObject2 // AtomQ     (* True *)          wdx = ExportString[arrayObject2, "WDX"];          reimported = ImportString[wdx, "WDX"]          (* Raw::string: String expected at position 2 in Raw[Language`ArrayObject,78 c4801b00000000]. >> *)     (* Raw[Language`ArrayObject, 78 c4801b00000000] *)          reimported // FullForm     (* Raw[Language`ArrayObject, Times[78, c4801b00000000]] *)          reimported // AtomQ     (* False *)          reimported // Depth     (* 3 *)          Uncompress[Compress[arrayObject2]]     (* "<---RAW DATA--->" *)          % // Head     (* String *)      Note that `Part` reports errors when invoked on a `RawArray`, but still is able to extract parts. `ArrayObject` has completely different representation in `InputForm` and `FullForm`, and turns into a `List` when reimported. Is this behavior normal? Or there are some bugs? Is it because these parts were not supposed to ever be seen by humans? Are there situations when one needs to explicitly construct or manipulate by `RawArray` or `ArrayObject` expressions? What is their real meaning?


Using Dot Product with InterpolatingFunctions

I am using NDSolve on a vector function $\mathbf y'(x)=f[\mathbf y(x)]$ with initial condition $\mathbf y_0$, where the dimension of the vector should be user-defined.               Clear[y, y0]     y0 = {1, 2}     sol = NDSolve[{y'[x] + y[x] == 0, y[0] == y0}, {y}, {x, 0, 10}]      I'm attempting to use the resulting InterpolatingFunction as an input into a matrix ODE, $\mathbf z'(x) = g[\mathbf z(x)]$, with initial condition $\mathbf z_0$.               Clear[z,z0]     z0 = {{1., 2.},{3.,4.}}     failing = NDSolve[{z'[x] + foo[y[x] /. sol, {1, 1}] z[x] == 0, z[0] == z0}, {z}, {x, 0, 10}]      Where               foo[vectx_?(VectorQ[#] &), vecty_?(VectorQ[#] &)] := vectx.vecty      The function `foo[x,y]` is failing to compute the dot product correctly because the dimensions don't match up (`Length[y[x] /. sol,]` is `1`), although `VectorQ[y[x] /. sol]` yields `True`. Naively, I expected that the result of `NDSolve` would be something like $\mathbf y(x) = (\text{InterpolatingFunction}[y_1(x)], \text{InterpolatingFunction}[y_2(x)],...)$ So that the dot product $\mathbf y \cdot (a,b,...)=a \, \text{InterpolatingFunction}[y_1(x)] + b \, \text{InterpolatingFunction}[y_2(x)]+...$ Rather, it's something more like `{InterpolatingFunction[{{0.,10.}},<>][t]}`, which is trivially a vector since it's enclosed by `{...}`. How do I express my "dot product" logic above in Mathematica-ese? Or is there a more elegant way to get the code flow that I want?


Mean of Date variable data

I have hourly registered data as :               Sort[Join @@ data[[All, 3 ;;]][[All, All, 2 ;; 3]]]     output={{{2013, 6, 19, 12, 0, 0.}, 7980.}, {{2013, 6, 19, 13, 0, 0.},      7994.}, {{2013, 6, 19, 14, 0, 0.}, 7860.}, {{2013, 6, 19, 15, 0, 0.},      7722.}, {{2013, 6, 19, 16, 0, 0.},  7602.}, {{2013, 6, 19, 17, 0, 0.},      7479.}, {{2013, 6, 19, 18, 0, 0.}, 7354.}, {{2013, 6, 19, 19, 0, 0.},      7319.}, {{2013, 6, 19, 20, 0, 0.}, 7347.}, {{2013, 6, 19, 21, 0, 0.},      7071.}, {{2013, 6, 19, 22, 0, 0.}, 6928.}, {{2013, 6, 19, 23, 0, 0.}, 6854.},      {{2013, 6, 20, 0, 0, 0.},6559.}, {{2013, 6, 20, 1, 0, 0.}, 6145.},      {{2013, 6, 20, 2, 0,0.}, 5920.}, {{2013, 6, 20, 3, 0, 0.}, 5686.},      {{2013, 6, 20, 4, 0, 0.},5696.},      {{2013, 6, 20, 5, 0, 0.}, 5901.}, {{2013, 6, 20, 6, 0, 0.},     6684.}, {{2013, 6, 20, 7, 0, 0.}, 7368.}, {{2013, 6, 20, 8, 0, 0.},     7699.}, {{2013, 6, 20, 9, 0, 0.}, 7884.}, {{2013, 6, 20, 10, 0, 0.},      7958.}, {{2013, 6, 20, 11, 0, 0.},{ 7984.}, {{2013, 6, 20, 12, 0, 0.},      7930.}, {{2013, 6, 20, 13, 0, 0.}, 7792.}, {{2013, 6, 20, 14, 0, 0.},      7588.}, {{2013, 6, 20, 15, 0, 0.}, 7479.}, {{2013, 6, 20, 16, 0, 0.},      7349.}, {{2013, 6, 20, 17, 0, 0.},  7253.}, {{2013, 6, 20, 18, 0, 0.},      7171.}, {{2013, 6, 20, 19, 0, 0.}, 7106.}, {{2013, 6, 20, 20, 0, 0.},      7044.}, {{2013, 6, 20, 21, 0, 0.}, 6711.}, {{2013, 6, 20, 22, 0, 0.},      6647.}, {{2013, 6, 20, 23, 0, 0.}, 6648.}}      I want to have the mean of the each day and the same time consequences just exclude the hours.Could you please help on the code.


A Graphics`Mesh`ConvexHull[] peculiarity

I have been unable to explain the behavior of `Graphics`Mesh`ConvexHull[]` on the following (highly simplified) example:               pts = {{-1/6, -1/18}, {-4/31, 1/9}, {-1/26, -12/73},            {1/6, 2/37}, {1/26, 12/73}, {4/31, -1/9}};          Graphics`Mesh`MeshInit[];          idx = ConvexHull[pts];          idx2 = Most[First[FindCurvePath[pts]]];          GraphicsRow[{Graphics[Line[pts]], Graphics[Line[pts[[idx]]]], Graphics[Line[pts[[idx2]]]]}]      I get the following result on my system (version 8.0.4 on Linux, if it matters): ![convex hull attempts on my points](http://i.stack.imgur.com/LnKJm.png) As you can see, `ConvexHull[]` does not seem to work properly on my set of points, while `FindCurvePath[]` has no problem. However, I had wanted to use `ConvexHull[]` because it consistently orders points in an anticlockwise manner (or at the very least it seems to), while `FindCurvePath[]` sometimes orders points clockwise. I can break down and just implement the Graham scan myself, but I'd prefer to understand why the hidden convex hull routine is not behaving in the manner I expect.


How do I generate the Mathematica Version 2 Spikey in Mathematica?

As we all know, _Mathematica_ changes its logo design with every new version, while still maintaining the dodecahedral/icosahedral motif. I have been able, through much digging around, to finally acquire the code for generating the logos corresponding to versions three, four, and five. I was able to obtain code for generating the version six logo from this blog post by Michael Trott (it is also available here). However, I have not been so successful in finding code for the version two logo: ![version 2 spikey](http://i.stack.imgur.com/FZeNo.gif) Some searching seems to indicate that there is code for this in one of the _Mathematica_ Guidebooks by Trott, but the libraries I have access to do not have copies of these tomes. (Google Books will also not let me preview the pages where the code seems to be.) I have also tried sending an e-mail to Michael Trott and Igor Rivin, but I have not gotten any response from them in three weeks, so it would seem that they are unable or unwilling to supply the code for generating the version two logo. So, **how might I generate the version 2 _Mathematica_ spikey?**


What does the VertexMoving method for FindGraphCommunities do?

I've been applying the VertexMoving method to some graph data, and it's producing very useful results. However, I've got no clue as to what this method actually _is_ , and the documentation is spectacularly vague. Does anyone know what this method does?


Find local maximum in 3D list

I have a set of data of the kind {{$x_i$, $y_i$, $z_i$}, ...} at randomly chosen points $x_i, y_i$. The $z_i$ are supposed to be a smooth function of the $x_i$ and $y_i$. Unfortunately they turn out not to be. A few points stick out. These are local extrema - I want to find them and remove them from the data set. The problem is that the $x_i$ and $y_i$ are chosen randomly, so I cannot choose nearest neighbors for comparison easily. Are there any methods to find the nearest neighbors in a given list, or even directly to find the local maxima in a random grid?


How do I delete items at the same position from every sub-list within a list?

We have data in a list called `megadata` where `megadata[[1]]` for instance are the temperatures of each data point, `megadata[[2]]` are the pressures, etc. We are trying to selectively remove data points to see how it changes our fits but I have been unable to get `Delete` or `Drop` or anything else to work. I need something to let me remove the same position from every nested list within the list. So for instance if I wanted to delete positions 2 and 3 I need something to change `megadata = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}` into `megadata = {{1, 4}, {5, 8}, {9, 12}. Edit: I'm really new to Mathematica (learning ahead of the semester as part of undergraduate research) so I'm having trouble understanding some of the comments made. I used the Drop[#, {2, 3}] & /@ megadata idea and it worked quite nicely for removing adjacent points but my nested lists have a length of 12 and when I would try using it as Drop[#, {4, 7}] & /@ megadata, it seemed to remove all the points between 4 and 7 (so it would remove 4,5,6, and 7). Is there anyway to modify this format slightly to make it not remove that whole range of points and only remove 4 and 7? Edit 2: I actually think I found the answer. Didn't see the link to the duplicate answer above. Sorry real new to all of this. Thanks for all the help though!


Counting elements which are inside another element on a different colour channel

I have a 3-channel image which shows red and green points (certain labelled proteins) inside blue regions (cell nuclei). After applying some segmentation filters, the resulting image is as follows: ![enter image description here](http://i.stack.imgur.com/n6Eit.png) The regions circled in blue are separated into components following steps similar to those mentioned in this guide Count Cells The red and green points are also both separated into components. What would be the best way to count those red and green points which are bound by the blue components?   -EDIT- What I mean is counting the points per blue-bound area, not the entire image as a whole. Sorry for the confusion. A rather brute-force method would be to call SelectComponents with a Do loop using the Label attribute of the components and use that as a mask. Is there a better and more efficient method of doing this?               Do[mask =         Image[SelectComponents[nuclei, "Label", # == nucList[[i]] &]];        redFoci =         ComponentMeasurements[         SelectComponents[ImageMultiply[redChan, mask], "Count",           2 < # < 100 &], "Centroid"];        greenFoci =         ComponentMeasurements[         SelectComponents[ImageMultiply[greenChan, mask], "Count",           2 < # < 100 &], "Centroid"];        AppendTo[fociList, {Length[redFoci], Length[greenFoci]}];       , {i, Length[nucPos]}];     Print[fociList];


Can we compile using only Integers Of Unusual Size?

I coined Integers Of Unusual Size to mean "bignum" using GMP, the underpinning of _Mathematica's_ ability to craft very big numbers. I have these functions from this question:               ascendingQ[x_] := 3 == Mod[x, 4]     uniqueQ[x_] := 0 != Mod[2 x - 1, 3]     uniqueRank[n_, m_] := Block[{a = If[1 != n && OddQ[n], n - 1, n]},        (n + IntegerExponent[a, 2]) 2^m - 1]        The first two need "bignum" inputs and the third needs "bignum" output And I have this variation of `countOrbit` which we will use for our research:               totalOrbit[x_] :=       Block[{h = x, t, c = 0, m, n, mt = 0, nt = 0},       While[1 != h,        h = (t = -1 + (3/2)^(m = IntegerExponent[h + 1, 2]) (h + 1))/          2^(n = IntegerExponent[t, 2]);        mt += m;        nt += n;        ];       c = 2 mt + nt       ]      This needs "bignum" everywhere. When we get a sufficiently frisky `totalOrbit` I will recast `countOrbit`. After I execute the compiled `totalOrbit`, I get error messages about exceeding machine precision,               cto = Compile[{x}, totalOrbit[x]]      so, I need a way to indicate that all numbers are "bignums."


Obtaining a particular form of solution for an integral

When I do:               Integrate [E^(-(t/\[Tau])) Cos[\[Omega] t], {t, 0, \[Infinity]}]      How could I get the solution in the form:               \[Tau]/(1 + \[Omega]^2*\[Tau]^2)


Unable to save changes in Option Inspector from one session to another for the Documentation Center

I wanted to change the global option "WindowsSize" to the "large" value using the Option Inspector. It works well for the current session. But then I realize the "Apply" button was greyed and not functional, so I could not save this change for another session. So my question is: why is the "Apply" button not available in the Option Inspector window? Did I inadvertently mess up something? My version of _Mathematica_ is 9.0.1.and I was trying to change the notebook options of the Documentation Center (making the "WindowsSize" option "Large" by default, because I was obliged to resize it each time I opened it) I am using OSX


Evaluate only one from a set of procedures

Let's say I've got a list of procedures:               {Print[1];, Print[2];, Print[3];}      And I want to only evaluate 3rd one:               {Print[1];, Print[2];, Print[3];}[[3]]      > >     1... 2... 3... >   Well, that's not what I've wanted, the walkaround would be to use `Hold`:               Hold[{Print[1];, Print[2];, Print[3];}][[ 1, 3]]      > >     3 >   **My question is:** is there more "proper" way to do this? p.s. the most tidy what I thought of is `Switch`:               Switch[2,      1, Print[1],      2, Print[2],      3, Print[3] ]      > >     2 >


Elegant way for map a function over the columns of an array

I have an array               data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};      And I want map `Standardize` over the column of the array. I use following code               Composition[       Transpose,       (Standardize /@ #)&,       Transpose][data]      > >     {{-1, 0, 1}, {-1, 0, 1}, {-1, 0, 1}} >   Is there more shoter way to get that result? PS: maybe using of `MapThread`, but function `Standarize` take a list as input. **EDIT** I have picked a bad example. Use this example:               data = {{-4, -8, -8}, {-9, 4, 10}, {-3, -9, 0}}      The result I desire:               {{0.4147806779,-0.5068532453,-0.9609876522},{-1.140646864,1.151939194,1.034909779},{0.7258661863,-0.6450859486,-0.0739221271}}


How can I use SelectComponents to select for components that have a pixel within a certain RGB range within their convex hull?

I calculate a set of morphological components:               Components = MorphologicalComponents[Binarize[image,0.1]];      We can now use SelectComponents to filter for components satisfying some metric, for example:               ChosenComponents = SelectComponents[Components, "Elongation", # <= 0.5 &];      However, is there a way to use SelectComponents to select for components that have a pixel within a certain RGB range in their convex hulls? For example, could we select for only the components that have a pixel with a "red" component of 0.2?


Is there the full Wolfram Language in Mathematica?

Today I read the new entry on WolframBlog with all it's nice little demos. I was realy interested in those with astronomic informations, but trying these with my own Mathematica I was irritated: Steven Wolfram wrote in the blog: "... You can use the Wolfram Language completely interactively, using the notebook interface we built for Mathematica." So I typed, like he did:               In: Sunrise[]     Out: Sunrise[]      So I didn't get the result in the blog. Same with other demos from the blog. So my question is: How can I use Wolfram Language with Mathematica? And how can I get it? (Yes I know, with indirections (WeatherData) I could do it with Mathematica too, but I wanted to do it like in the blog's demos.)


Trying to show an expression is always zero

I have a symbolic matrix $$m = \begin{pmatrix}A1 & B1 & C1\\\A2 & B2 & C2 \\\ A3 & B3 & C3\end{pmatrix}$$ and I believe that `Det[m]` is always zero (i.e. [A3 B3 C3] is a linear combination of [A1 B1 C1] and [A2 B2 C2]). The expressions for the A's, B's, and C's that I have are fairly complex, so by the time you multiply all the terms to get the determinant the expression is huge. I have tried substituting random numerical values for all of my symbols and the numerical result of the determinant is indeed very small (O(10^-12)), and graphically all of the lines that I've seen produced in this form intersect at the same point, so I'm quite convinced this should be zero, but I just want something to show me "yes, it is actually zero" before I proceed with this assumption in further work. I'm not sure how to post a .nb file, so I've simplified what I have to plain text. Does anyone know how to show that det[m] = 0 without substituting numerical values for all of the symbols remaining (and obtaining very small, but unfortunately non-zero, values)?               A1 = x1*D23 + x2*D31 + x3*D12     B1 = y1*D23 + y2*D31 + y3*D12     C1 = -.5*(D12*D23*D31 + (x1^2 + y1^2)*D23 + (x2^2 + y2^2)*D31 + (x3^2 + y3^2)* D12)          A2 = x1*D24 + x2*D41 + x4*D12     B2 = y1*D24 + y2*D41 + y4*D12     C2 = -.5*(D12*D24*D41 + (x1^2 + y1^2)*D24 + (x2^2 + y2^2)*D41 + (x4^2 + y4^2)* D12)          A3 = x2*D34 + x3*D42 + x4*D23     B3 = y2*D34 + y3*D42 + y4*D23     C3 = -.5*(D23*D34*D42 + (x2^2 + y2^2)*D34 + (x3^2 + y3^2)*D42 + (x4^2 + y4^2)* D23)          m = {          {A1, B1, C1},          {A2, B2, C2},          {A3, B3, C3}         }          determinant = Det[m]          D12 = D2 - D1          D13 = D3 - D1          D14 = D4 - D1          D23 = D3 - D2          D24 = D4 - D2          D34 = D4 - D3          D21 = -D12          D31 = -D13          D32 = -D23          D41 = -D14          D42 = -D24          D43 = -D34          D1 = Sqrt[(x0 - x1)^2 + (y0 - y1)^2]          D2 = Sqrt[(x0 - x2)^2 + (y0 - y2)^2]          D3 = Sqrt[(x0 - x3)^2 + (y0 - y3)^2]          D4 = Sqrt[(x0 - x4)^2 + (y0 - y4)^2]          Random numerical substitutions          x1 = 3.4     y1 = 5.6     x2 = 7.8     y2 = 1.2     x3 = 8.3     y3 = 9.1     x4 = 7.2     y4 = 5.9     x0 = 14.08     y0 = 2.34          In[58]:= determinant          Out[58]= 7.27596*10^-12


Extract function arguments

Is there a way to extract the arguments of a function? Consider the following example: I have this sum               g[1] + g[2] + g[3] + g[1]*g[3] + 3*g[1]*g[2] + 6*g[1]*g[2]*g[3]      Now, what I want to do is exctract the function arguments and apply them to another function `func` which takes the arguments as a list.               func[{1}] + func[{2}] + func[{3}] + func[{1, 3}] + 3*func[{1, 2}] + 6*func[{1, 2, 3}]      I know there is `Extract[g[1]*g[3], Position[g[1]*g[3], _Integer]]` but that does not work if I have a multiplicative constant. Is there a way to do this?


Combinations which do not have elements in common

I can choose 2 letters from the four letters $\\{A,B,C,D\\}$ in 6 combinations using the combination formula $$\frac{n!}{ r! (n-r)!}$$               {A, B}, {A, C}, {A, D}, {B, C}, {B, D}, {C, D}      Consider now the collection of all _subsets_ of a set of $n$ elements and restrict to those having exactly cardinality $k$, such as $k=2$ above. How can I find all combinations of groups of 2 or 3 or ... or $n$ (should be dynamic) of these which do not have letters in common? So, for example, I am expecting the result for combinations of two groups of $k=2$ elements to be the three collections below:               {{A, B}, {C, D}},          {{A, C}, {B, D}},          {{A, D}, {B, C}}      This is just a small example but I would like the algorithm to work for a large number of sets (I have more than 35000 sets).


Use MATHEMATICA to calculate the volume of the solid that results when the region enclosed by the given curves is revolved about the x- axis. f(x)=Pi^2 Sin[x] Cos[x]^3, f(x)= 4 x^2 x=0, x=Pi/4


MatrixForm control inside Row[]

I would like to pretty print two column vectors of different lengths so that they are aligned at the top rather than centered, which seems to be the default. For example,               v1 = {a, b, c, d, 0, 0, 0}; v2 = {a, b, c, d};     Row[{MatrixForm[v1], MatrixForm[v2]}, Alignment -> {Center, Top}]      results in the pretty printing of the vectors but they are actually centered in the row rather than aligned with the horizontal position at the top. Using a GraphicsRow instead of Row does work but changes the fonts from the rest of the nb so is only a second best solution. Is there some other approach to this that I could try?


Specifying mesh in NDSolve

I am trying to solve a system of one-dimensional two-point boundary-value problems with NDSolve. I would like use a fixed mesh (specified by me) in the calculation. Is there a way to do this? The mesh can be uniformly spaced. Thanks!


Fitting a two-dimensional Gaussian to a set of 2D pixels

Imagine I have a set of data like the following:               data = {{0.0453803, 0.0427863, 0.0489815, 0.045243, 0.0488289, 0.0432898,        0.04448, 0.0387732, 0.0388952}, {0.0507668, 0.0427863, 0.0502632,        0.0503395, 0.0634623, 0.0675822, 0.0529335, 0.047425,        0.0387121}, {0.042237, 0.0501259, 0.0595712, 0.0869001, 0.139559,        0.141512, 0.0868391, 0.0579232, 0.0408331}, {0.0478981, 0.0491646,        0.0652628, 0.130404, 0.218448, 0.220645, 0.143603, 0.0605173,        0.0424964}, {0.0462043, 0.0530861, 0.076051, 0.140017, 0.206943,        0.202502, 0.118791, 0.0614023, 0.0459907}, {0.0511788, 0.0582132,        0.105531, 0.166354, 0.181003, 0.13698, 0.0748302, 0.0557107,        0.0492103}, {0.0493629, 0.0539712, 0.0971695, 0.160769, 0.164477,        0.104768, 0.0591745, 0.0475319, 0.0452583}, {0.0510719, 0.0599374,        0.0730602, 0.0975814, 0.101289, 0.0691997, 0.0498054, 0.044892,        0.043122}, {0.0460517, 0.0567025, 0.0574044, 0.0587778, 0.0537118,        0.0487221, 0.0474098, 0.0413977, 0.04477}}      I don't have enough reputation to post an image, but one can easily be generated by applying `ListPlot3D` to the above data set. How might I best fit a Gaussian curve to this set of datapoints, and extract properties such at the fit' semi-axes? I noticed that `ComponentMeasurements` has some functionality for best fit ellipsoids, but that doesn't seem to be workable here. My objective here is to determine how "Gaussian" a set of points in an image are. My strategy is to sequentially fit a 2D Gaussian to each point, and then to measure it's eccentricity and spread (looking, for example, at the length and ratio of the semiaxes of the ellipsoid corresponding to the fit). The example here seems like it should yield a 2D Gaussian fit with significant spread and a ratio for the semiaxes significantly diverging from one.


How to approximate a computationally expensive 5-dimensional manifold?

I have a 4-parameter family of functions, which I'll refer to as `y[a, b, c, d][x]`. In this notation, `a, b, c, d` are the 4 parameters, and `y[a, b, c, d]` is a function $\mathbb{R}\to\mathbb{R}$. I would like to implement a `Manipulate`-based widget, with one slider for each of the 4 parameters, that will show a 2-D plot of `y[a, b, c, d][x]` vs `x` for any given setting of the parameters. The hitch is that the functions `y[a, b, c, d]` are very time-consuming to compute. Each plot would take about 1 minute to generate, which rules out any interactive exploration. Luckily, the functions `y[a, b, c, d]` appear to be rather smooth, so I'm wondering if there is some way to approximate the ensemble with some easier- to-compute "spline-like" functions `yApprox[a, b, c, d]`. My naive thinking about this begins with a pre-computed mesh of points of the form               {a, b, c, d, x, y[a, b, c, d][x]}      ...but I'm not sure how to use such a mesh to generate an ensemble of continuous functions `yApprox[a, b, c, d]` varying continuously over the parameters `a, b, c, d`.


Discontinue, then continue x-axis of 2D Histogram

I have the pictured Histogram. It was generated by the following lines:               H = ExampleData[{"NetworkGraph", "HighEnergyTheoryCollaborations"}]     Histograms`Histogram[Length /@ ConnectedComponents[H], Histograms`HistogramRange -> {0, 25}, AspectRatio -> 2, BaseStyle -> 10]      ![enter image description here](http://i.stack.imgur.com/yvKDy.png) I cut the x-axis at 25 because there is only one y(x)>0, x>25: x=5835. A better solution would be to cut x at 25, then continue x at 5834 and end it again at 5836. How can I achieve this?


Why does Integrate declare a convergent integral divergent?

When I try this command               Integrate[1/Sqrt[(s^2 - u)^2 - 1], {s, m, Infinity}, Assumptions -> u > 2 && m > 10]      _Mathematica_ declares that the integral does not converge on `{m, ∞}` The integral, though, is clearly convergent, and _Mathematica_ has no trouble evaluating it at any value of $u > 1$. A command such as               Integrate[1/Sqrt[(s^2 - 20.1)^2 - 1], {s, m, Infinity}, Assumptions -> m > 10]      works fine.


'kEINVALErr' error on startup

I have been using _Mathematica_ 8 on an OS X system for quite a while now, but this morning it threw this error at me when I started the program up: > Assertion 'kEINVALErr' failed at LikeResource.c:56 A search (`sudo find / -name "*Resource.c"`) of this computer reveals no such file. I asked the admin to re-install _Mathematica_ from scratch, but even after he did so the error popped up as soon as I tried to launch it. Any thoughts? Thanks in advance!


Ploting fourier transform

I want to Find the fourier transform of this graph. {ListLinePlot[hari, PlotRange -> {{0, 200000}, {-1.5, 1.8}}]} ![I want to Find the fourier transform of this](http://i.stack.imgur.com/IFKFx.jpg) And when I Put: ListLinePlot[Abs[Fourier[hari][[2 ;; 100]]], PlotRange -> All, DataRange -> {2, 100}] The result show me this. ![I don't know what i am doing wrong here.](http://i.stack.imgur.com/txqfV.png) And i don't know what i am doing wrong here.


How do you configure Mathematica 9 to automatically evaluate all notebooks?

I have a Mathematica 6 course that I am using in Mathematica 9; there is no updated version. Every time I open a notebook I have to go to the Evaluation menu and click on "Evaluate Notebook". Is there a way for me to set it so that it automatically evaluates a notebook upon my opening it? I keep getting answers on shortcuts I can use once the notebook is open or pressing shift- enter on a cell but that's not an answer; I would like not to do anything at all other than open the notebook and have every cell evaluated already since the tutorial course is long and contains a ton of notebooks.


FindProcessParameters for Fractional Brownian Motion Returns Error

I have the following data:               x={11.477, 5.9009, 3.77, 12.171, 9.7534, 12.905, 6.933, 4.6517, 7.601, \     3.5294, 13.086, 7.5675, -0.1665, 5.2741, 7.657, 12.536, 2.2046, \     3.0679, 10.777, 13.505, 15.199, 14.02, 10.36, 14.502, 22.701, 22.733, \     23.34, 22.694, 22.222, 19.866, 18.393, 11.18, 8.936, 12.689, 5.2338, \     4.6382, 9.5113, 4.2222, 4.8046, -0.2615, 26.651, 2.6889, 14.937, \     7.7831, 18.225, 23.549, 13.313, 9.3008, 3.6867, 12.954, 11.04, \     19.219, -3.3798, 13.351, 14.368, 13.044, 14.143, 21.393, 23.952, \     22.603, 14.976, 20.189, 23.61}      When executing FindProcessParameters as follows in Mathematica 10:               FindProcessParameters[x, FractionalBrownianMotionProcess[h]]      I get the following error:               FindProcessParameters::invproc: Estimated process parameter(s) yielded an invalid process. >      Any ideas on why?


Finding intersection and graphing

1) How do I find the intersection of `f[c_] := y^2 - 2 x^2 (x + 3) == c ((y + 1)^2 (y + 9) - x^2)` between the plots of f[0] and f[2] I tried plugging-in numbers. But I can't seem to find the intersections 2) Also how do I graph this http://i.imgur.com/MjwmLCC.jpg ? I figured out the equation to be `y=x^2-9` but I don't know what to do next.


System of Nonlinear equations with Gamma and Incomplete Gamma function

The next two nonlinear equations are cumulative ratios of a production system. The mathematical model includes two essential parameters (n, tau) that can be obtained by solving this system. I'm trying to solve it in Wolfram Mathematica 10 (WM10). But looks like it cannot give the right solution. The equations are:               f21[n_?NumberQ, tau_?NumberQ] =       Gamma[1/n] - Gamma[1/n, (23.5/tau)^n])/       (Gamma[1/n] - Gamma[1/n, (11.5/tau)^n]);     f31[n_?NumberQ, tau_?NumberQ] = (       Gamma[1/n] - Gamma[1/n, (35.5/tau)^n])/       (Gamma[1/n] - Gamma[1/n, (11.5/tau)^n]);      These ratios have the correspondant values.               r21 = 1.563;      r31 = 1.985;      n must be greater than 0 and less than or equal to 1, and tau must be greater than 0. These search limits can be established as:               nlow = 0.1; nhigh = 1.;     taulow = 0.1; tauhigh = 20.;      Of course, in order to solve the equations, those must be in a consistent manner and equaled to zero. Something like this:               f21[n, tau] - r21 = 0     f31[n, tau] - r31 = 0      But the problem comes here, when your write this code and try to solve the system through FindRoot nothing comes as a solution, WM10 says: "no interpretations available". Furthermore, the introduced equations seem to have been accepted as such by WM10.               FindRoot[{f21[n, tau] - r21, f31[n, tau] - r31}, {n, 0.5, nlow, nhigh}, {tau, 5., taulow, tauhigh}]      I'll appreciate any comment in order to help the solution of this problem. Thank you. Best regards.


Why do I get Floor and Ceiling in my output despite my assumptions

I am trying to simplify the following expression.               Sum[       Binomial[2 k, m] (1 + (-1)^m)/2 Beta[(1 + m)/2, (n - 2)/2]          (Gamma[(1 + m)/2] Gamma[1/2 (-1 + 2 k - m + n)])^2 ,        {m, 0, 2 k}]      Before doing it, I first set the `$Assumptions = {n ∈ Integers, k ∈ Integers};` since I know `n` and `k` are integers. The answer I got from _Mathematica_ v10 was rather complicated. However, one thing I found strange was that the solution contains `Floor[k]` and `Ceiling[-k]` that are clearly just `k` and `-k` since they are integers. What is more strange thing is I get an error if I try to further simplify it. What is the precise way to achieve this goal?


How to set initial guess in NDSolve

I'm trying to solve a BVP using NDSolve and I want to impose the starting initial guess. I googled and looked at the help, but I couldn't find this option.               NDSolve[{       A[u[x]] u''[x] == F[x],       u[0] == u0,       u[1] == u1        },u[x],{x,0,1}]      where A[u] = u^2 + u^3 + u^4 or something like that. How can I set the starting guess? Thanks in advance for all your advices. Petrus


Plot sphere not centered at the origin?

I can plot a sphere of the form x^2 + y^2 + z^2 = ...., but when I try:               RegionPlot3D[(x - 1)^2 + (y - 2)^2 + (z - 3)^2 = 14, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}]      I get an error: > >     Set::write: Tag Plus in 4. +9. +16. is Protected. >> >   which I don't understand at all. I can't find examples of such equations plotted either.


Evaluation of integral

I want to evaluate an indefinite integral using the Integrate command, and I know that the answer can be written in terms of elementary functions (square roots, logs etc.) but _Mathematica_ seems to give the answer in terms of a Hypergeometric2F1 function. How do I get it to give me the answer in terms of the elementary functions? The integral is the following: $$ \int \sqrt{\left(\frac{w}{2}\right)\left(\frac{w}{2}+u+v\right)} \ \mathrm{d}w $$ Thanks!


About TetGenTetrahedralize Mesh Size

I have used TetGenTetrahedralize to generated a cubic mesh. I want that the edge size of the triangle to be 0.2, how can realized this? And What does the word "pq1.414a1" mean? inst1 = TetGenTetrahedralize[ inst, "pq1.414a1"]               Needs["TetGenLink`"];     Needs["ComputationalGeometry`"];          long = 15;     broad = 15;     height = 15;          inst = TetGenCreate[];          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}}};          TetGenSetPoints[inst, pts];     TetGenSetFacets[inst, facets];          inst1 = TetGenTetrahedralize[ inst, "pq1.414a1"]     elemPts = TetGenGetPoints[inst1];     elemFaces = TetGenGetFaces[inst1];          Graphics3D[GraphicsComplex[elemPts, Polygon[elemFaces]]]


Why does Sort fail in this simple example?

I'm sure I'll be embarrassed by the answer, but I don't understand why I get the following result:               list = {{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}        This works:               Sort[list]       (* {{4, "a"}, {5, "w"}, {6, "k3"}, {7, "k4"}, {9, "b"}}*)      This works:               Sort[list, #1[[1]] > #2[[1]] &]        (*{{9, "b"}, {7, "k4"}, {6, "k3"}, {5, "w"}, {4, "a"}}  *)      But this fails:               Sort[list, #1[[2]] < #2[[2]] &]        (*{{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}*)      **Question:** Why would it work using `SortBy[]` and not `Sort[]`?


singularity in NDSolve for some values of parameter

my equation is:               k[a_?NumericQ, b_?NumericQ, c_?NumericQ] := NDSolve[{r^3 b x''[r] y[r] - 12 x[r] y[r] -       4 r^3 b y''[r] x[r] == 0, 4 (2 x'[r]^2 +          2 x[r]x''[r])/Sqrt[c] + (2 y'[r]^2 +          2 y[r] y''[r])/Sqrt[c] == -4b/r,x[1] == 0, y[1] == Sqrt[-4 b Log[2/b]/(c^(-1/2))],     y'[1] == c^(1/4) (-4 b - 4 b Log[2 /b])/(2 Sqrt[-4 b Log[2/b] ] ), x'[1] == a},      {x, y}, {r, 1, b/2}, MaxSteps -> 1000000]      and then I plot it:               Plot[Evaluate[{x[r], y[r]} /. k[1, 50, 10^(-7)]], {r, 1, 25}]      ![enter image description here](http://i.stack.imgur.com/xHPTN.gif) this one is okay, cause `x[r]` and `y[r]` both equal to 0 at `r=b/2` if I set `a=0` and the other parameters stay the same ![enter image description here](http://i.stack.imgur.com/I3Rt5.gif) I do not know how comes this sigularity at `r=b/2`, basing on the second equation in NDSolve, `4 (2 x'[r]^2 + 2 x[r]x''[r])/Sqrt[c] + (2 y'[r]^2 + 2 y[r] y''[r])/Sqrt[c] == -4b/r` comes from the second derivative of `r` in this equation: `c^(-1/2) 4 x[r]^2 + c^(-1/2) y[r]^2 == -4 r b Log[(2 r)/b]` so it's easy to check, if `x[r]=0` all the way, `y[r]` should be `0` at `r=b/2` does anyone know how to resolve the infinity at `r=b/2` for any values of the parameter? `a>=0, b>2, 10^(-3)>c>10^(-7)` thanks a lot


Find a sequence of integers which give max in each step

I would like to write a program in _Mathematica_ to look for the integer $n$ such that the following definition holds for any $1 < m < n $ $$\frac{f(n)}{f(m)}>1+\frac{\log(n/m)}{\log(n) \log(\log(m))}$$ where $f(n)$ is for example number of divisors of $n$ (and also count the number of resulting sets). I wrote the following code, but the problem is that when it finds the first `j1` in the next step of the `For`, it looks for the value `j2` for which $$\frac{f(j_2)}{f(j_1)}>1+\frac{\log(j_2/j_1)}{\log(j_2) \log(\log( j_1))}$$ but I want it to find the `j2` such that $$\forall j,\ j_1 \le j < j_2 \implies \frac{f(j_2)}{f(j)}>1+\frac{\log(j_2/j)}{\log (j_2) \log(\log(j))}$$ **Note** : In the following example `k[*]` is a special and known sub sequence of integers.               i = 20;          count = 0;          list = {i};          For[j = i, j <= 100, j++,              If[ f[k[j]]/f[k[i]] > 1 + Log[k[j]/k[i]]/(Log[k[j]] Log[Log[k[i]]]), i = j;              AppendTo[list, i];             count = count + 1         ]     ];          list          Print["count= ", count]


Convert quoted printable aka PrintableASCII characters to UTF-8

I have several .eml email files to import. Some of them were saved as quoted- printable 7-bit encoded. I skipped through the _Mathematica_ documentation and found `ToCharacterCode` and `CharacterEncoding`. However,               Import[foo.eml, CharacterEncoding -> "PrintableASCII"]       does not lead to conversion of the 7-bit characters to the default set (8-bit I guess). In particular, I want to get rid of encodings like `=FC`, which is a German Umlaut-u (`ü`). After that I would like to be able to proceed with normal text analysis. Does anybody have experience with the right functions?


Format Preservation of FullSimplify on Indexed System of Autonomous Equations

I currently have a large system autonomous differential equations. I've indexed a more managable dummy system of identical form, using `Part` to reference each individual equation, so:               eqns = {c1' == -kf*c1 + kr*c2, c2 == kf*z1 - kr*z2 - kf*c2, c3' == kp*c2}      with _each_ LHS denoted `cn'` where n ranges from 0 to 3 (or the # of equations). Inputting `eqns[[1]]` yields:               c1' == -a kf + b kr      Whereas inputting `FullSimplify @ eqns[[1]]`yields `kf c1 + c1' == kr c2`. Does anyone know a way to specify that the format ought be maintained, ie. **_`Some Input`_** which would isolate c1' in the `FullSimplify` term, or yield `c1' == kr c2 - kf c1` This sounds petty and _is_ in this dummy example, but isn't for larger systems. Thank you in advance. **_Edit:_** I've spent awhile digging around online and in the help to no avail other than _possibly_ changing my notation format, which would render my future use of NDSolve, where I hope to use the shorthand of `eqns`, problematic given Mathematica's understanding of prime notation for derivatives. (Also, another complication in changing the LHS notation of `c1', ..., cn'` is in that each is an implicit (rather than explicit) function of (t) ( _see my attached link in line 1)_ , and so in NDSolve each `cn'` and `cn` must be appended with a `[t]` on the end at some point in the `NDSolve` function.


Assume function is real valued

I want to create a function returning subscripted symbols and I want these symbols to be assumed real. How do I do that?               ClearAll[Evaluate[Context[]<>"*"]]          d[n_]:=If[OddQ[n],Subscript[d,n],0]          Map[Re[d[#]]&,Range[1,5]]          (* {Re[Subscript[d, 1]],0,Re[Subscript[d, 3]],0,Re[Subscript[d, 5]]} *)


Returning all positions for all different occurences of elements in a list

Is there way to construct oneliner as pure function(s), so that I enter `mylist` only on one place - on the end of line. And that function return the same result as last line bellow but paired with `mylist`. So the result should look like this: > >     {{1, {8}}, {2, {2, 4, 6}}, {4, {1}}, {5, {5}}, {7, {3, 7}}} >                 mylist = {4, 2, 7, 2, 5, 2, 7, 1};         alldiffelem = Sort@DeleteDuplicates@mylist         (* {1, 2, 4, 5, 7} *)     (Flatten@Position[mylist, #]) & /@ alldiffelem         (* {{8}, {2, 4, 6}, {1}, {5}, {3, 7}} *)


What is the best Mathematica tutorial for young people?

As Conrad Wolfram said at the TED conference, in the future kids should focus more on new technology. Computers compute better than humans, so we should focus more on thinking and getting the knowledge how to use available software. I teach programming to my young friend, he is 14. He is very talented, however he still has very much to learn. I wonder how I can teach them to use Mathematica to help with homework and maths materials... I finished my IT studies. I have only used Mathematica a few times, but I am not an expert.


given n lists, get list of applications of function to n-tuples

Is there a built in function or an easy rule to do the following transformation?               H[{A[0], A[1], ...},{B[0], B[1], ...},...]      into               {H[A[0], B[0]], H[A[1], B[1]], ...}


Representative Smooth Kernel Distribution from Truncated Distribution

I am trying to produce a better distribution from a dataset that is bounded to be greater than 0. Here is an example distribution from the documentation that mimics the behavior of the actual dataset:               data = RandomVariate[ExponentialDistribution[2], 10^4];     dist = SmoothKernelDistribution[data];     \[ScriptCapitalD] = TruncatedDistribution[{0, Infinity}, dist];     Plot[Evaluate@PDF[\[ScriptCapitalD], x], {x, -1, 5}, PlotRange -> All,       Filling -> Axis]      ![enter image description here](http://i.stack.imgur.com/emHon.png) As you can see, the peak of the SmoothKernelDistribution is not at 0, but at some value slightly greater than zero. The more points there are in the dataset, the closer the peak is to zero, as there will be a point in the dataset that is closer and closer to zero with more points. In the real dataset, I don't have the liberty of drawing more points, but I do know that the real dataset is restricted to be > 0. Using the standard histogram, the peak will be 0 given a large enough bin size, which I guess can be achieved in SmoothKernelDistribution by increasing the kernel width, but as far as I can tell SmoothKernelDistribution does not automatically set this width to avoid the above behavior. My question is: How do I generate a SmoothKernelDistribution which mimics the behavior of the underlying distribution?


Making a histogram of a user defined random variable

Suppose I want to generate a histogram of $n$ trials a slightly complicated random variable in _Mathematica_. Is there an easy way to do this? For instance, to make a histogram of a normal variable one can simple use               Histogram[RandomVariate[NormalDistribution[0, 1], 200]]      I want to create a histogram of a more complicated random variable. The random variable comes from random matrix theory, but its specific form is probably not so important. If we call it X, running               Histogram[RandomVariate[X, 200]]      returns > RandomVariate::udist: "The specification X is not a random distribution > recognized by the system." Indeed, even running               Histogram[RandomVariate[NormalDistribution[0, 1]^2, 200]]      returns this error message, and I think if I understood what's going wrong in this latter case my problem would be resolved also. There is a _Mathematica_ help page on the topic, but all the examples of random variables given there are for prepackaged probability distributions.


Fast Autocorrelation Computation

I want to compute the Autocorrelation Function (ACF) of a data table with $10^6$ entries. I know that there is a built-in function in _Mathematica_ for that, but because I do not know how exactly it is defined, I tend to avoid it. Furthermore, I need the autocorrelation for Fluorescent Correlation Spectroscopy (FCS), which is specifically normalized: $$G(\Delta t) = \frac{\displaystyle\sum_{i=0}^{M-m}I(i\tau)I(i\tau + m\tau)}{\langle I\rangle^2(M-m)}$$ where $\Delta t=m\tau$, $\tau$ is the step size, $M$ is the total numbers of steps. Can you help me to define it, so that the computation finishes in less than a day? This is how I generate my data with Mathematica                   n = 50.;         radius = 6.*10.^-8.;         k = 1.38*10.^-23.;         T = 293.;         Eta = 1.*10.^-3.;         d = (k*T)/(6.*\[Pi]*Eta*radius);         Deltat = 500000.;         time = 10.*10.^-6.;         Taud = (Omegar^2./(4.*d));         Omegar = 200.*10.^-9.;         Omegaz = 5.*Omegar;         Io = 1;         boundary = 5.*10.^-6.;         initial = boundary/2.;         step = Sqrt[2.*d*time];         RandomWalk[x_] :=            Accumulate[            Join[{RandomReal[{-initial, initial}, 3]},               RandomVariate[NormalDistribution[0, step], {x, 3}]]];         p = Table[Mod[RandomWalk[Deltat], boundary, -initial], {i, n}];         particleintensity =             Io Exp[(p^2).{-2/Omegar^2, -2/Omegar^2, -2/Omegaz^2}];         int = Total[particleintensity];         ListPlot[int, AxesOrigin -> {0., 0.}, AxesLabel -> {"t", "I"},              PlotRange -> Full, PlotRangeClipping -> False, PlotStyle -> Red]      I tried with the definition from Wikipedia: $$G(\tau)=\frac{\langle\delta I(t)\delta I(t+\tau)\rangle}{\langle I(t) \rangle^2}=\frac{\langle I(t)I(t+\tau) \rangle}{\langle I(t)\rangle^2}-1$$ which I implemented like this                   acff = Table[Mean[int.Take[PadLeft[int, t], Deltat]], {t, 1, Deltat}]         acf = acff/Mean[int] - 1      but this still takes ridiculously long time to compute.


Mathematica and gaps in continuous plot

I have a bit of trouble with Mathematica and it's plotting stuff. I tried to plot Jacobi amplitude function:               JacobiAmplitude[Sqrt[0.1]*x, 10], {x, 0, 50}]      but the result leaves gaps where the roots of the function should be (particularly for this function around `x = 3, 6, 10, ...`). I've done a bit of googling and found that either `Exclusions` set to `None` or raising `PlotPoints` should help. Well, it didn't. I even tried to set `MaxRecursion` to `8`, `PlotPoints` to one **million** , waited several hours for the plot and it didn't change. Funny thing is, that when I added `Mesh -> None`, I've found out, that mathematica added plot points even at the gaps, but it didn't join them with lines! This is something like bug, or how should I deal with that? Any help'd be appreciated. P.S.: I'm using Mathematica 9.0


Pure Functions with Lists as arguments

Assuming I have two function: example 1:               add[{x_, y_, z_}] := x + y - z     add[{1, 3, 5}]      If use pure function,I know I can write it as :               Function[{x}, x[[1]] + x[[2]] - x[[3]]][{1, 3, 5}]      example 2:               fun[{a_, b_}, y_] := If[y~Mod~2 == 0, {a~Join~{y}, b}, {a, b~Join~{y}}]     Fold[fun, {{}, {}}, Range@10]          Fold[Function[{x, y},        If[y < 5, {Join[x[[1]], {y}], x[[2]]}, {x[[1]],          Join[x[[2]], {y}]}]], {{}, {}}, Range[10]]      I think this a little prolix with many "[[]]", can you tell me another simpler way? **Updated**               Do[       If[i[[1]] < i[[4]] < i[[7]] &&          i[[1]]/(10 i[[2]] + i[[3]]) + i[[4]]/(10*i[[5]] + i[[6]]) +            i[[7]]/(10 i[[8]] + i[[9]]) == 1, Print@i        ],       {i, Permutations[Range[9]]}       ] // Timing     {2.153, Null}      ============               Do[If[(x /. {a_, b_, c_, d_, e_, f_, g_, h_, i_} :>            a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1),         Print@x], {x, Permutations[Range[9]]}] // Timing     {10.374, Null}     (*can't compiled*)      =============               Block[{a, b, c, d, e, f, g, h, i},       Do[        If[{a, b, c, d, e, f, g, h, i} = x;         a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1,          Print@x], {x, Permutations[Range[9]]}]       ] // Timing     {2.543, Null}     (*easy compiled*)     (*If Module or Blcok within Do loop, Module will slower than Block *)


Hakim's Sphere in Mathematica?

Hakim El Hattab's Sphere, consists of only a handful of lines of Javascript, and would probably be even terser if written in Mathematica. How difficult would it be to "transcode" Mathematica to JS? Further, what is necessary to write the Mathematica code on a desktop and program it to negotiate with ssh or sftp to actually upload the scripts to a web server? Sorry if being a bit vague here, just getting into the web services aspect.


How to avoid joining MathieuCharacteristicA in a plot?

In the documentation > As a function of the first argument, MathieuCharacteristicA is a piecewise > continuous function So how to avoid joining different pieces of the function? For example,               Plot[MathieuCharacteristicA[r, 1], {r, -2.5, 2.5}]      I get ![enter image description here](http://i.stack.imgur.com/6r6FQ.png) So why does Mathematica draw the vertical lines in default? And how to avoid drawing them except using a explicit setting such as `Exclusions -> 1`?


Omitting singularities from plot by specifying them in range

See the Mathematica 'basic plotting' documentation: http://reference.wolfram.com/mathematica/tutorial/BasicPlotting.html Scroll down to the third plot on that page, which says the following: "The singularities can be omitted from the plot by specifying them in the plot's range." According to this doc, if you enter this in Mathematica 9, you will get the result shown in that doc page:               Plot[Tan[x], {x, -3, -Pi/2, Pi/2, 3}]      But when I try it I get this `pllim` error: ![Mathematica graphics](http://i.stack.imgur.com/Sxjqt.png) claiming too many things appearing after `x`, but that's what the doc says to do. I have searched here for anything relevant to no avail. What's going on with this?


How can I italicize FrameLabel directives?

Suppose that I use `Frame -> True` in `Plot`. Then I can use `FrameLabel -> {"x (nm)", "y (nm)"}` to label the frame (i.e., "pseudo-axes"). For example, I have done the following:               Plot[Sin[x], {x, 0, 2 Pi}, PlotRange -> All,       Frame -> True, FrameLabel -> {"x (nm)", "y (nm)"},       BaseStyle -> {FontFamily -> "Arial", 20}]      ![FrameLabel](http://i.stack.imgur.com/4yZLL.gif) Now, however, I would like the characters "x" and "y" to be italicized in `FrameLabel`. Is this possible? I would like my labels to look like this: _x_ (nm) _y_ (nm) where _x_ and _y_ are italicized, but (nm) is not. Do I need to use `Style`, or is there a simpler solution? Also, in the future, I may need to create `FrameLabel` directives that are more complicated, such as: Phi( _z_ ) (V) where, for example, _z_ is italicized, but Phi( and ) (V) are not.


Plot lines keep disappearing

I'm trying to plot the _Compton Shift_ which I've defined as:               E2[ϕ_] := E1/(1 + (E1/(m*c^2))*(1 - Cos[ϕ Degree]))      I've initiated the constants and when I evaluate the function for various degrees, it gives me the correct answer. The issue I'm getting is that when I try and plot this function (with m = 1, c = 299792458 and E1 = 180), my plot shows a line until the value of ϕ is increased to above ~30-40. I'll get a flat line for small values of Phi but for larger values, the line disappears and I get a blank plot. What is the reason for this? Am I doing something wrong?


Use Simplify option Trig->False when 3rd argument to Collect is Simplify

I would like to simplify the following expression               AAA (4 Sin[x]^2 Cos[x]^2) + AAA 4 Sin[x] Cos[x] + AAA      with the `Trig->False` option inside a `Collect`:               Collect[AAA (4 Sin[x]^2 Cos[x]^2) + AAA 4 Sin[x] Cos[x] + AAA, AAA, Simplify]      how can I insert the `Trig->False` condition in such an expression? Thank you in advance


Riemann surface for cubic root

I'm trying to generate Riemann surfaces of higher order. I read How to visualize Riemann surfaces?, and the subsequent documents. I'm able to reproduce the surface using polar representation, but I'm having a difficult time generating them using rectangular coordinates, for roots greater then 2. So far what I have is:               p1 =       Plot3D[{Im[(x + I*y)^(1/2)], -Im[(x + I*y)^(1/2)]}, {x, -2, 2}, {y, -2, 2},         PlotPoints -> {40, 120}, Mesh -> 25, BoxRatios -> {2, 2, 2},         ColorFunction -> Function[{x, y, z}, Hue[z]]]          p2 =       ParametricPlot3D[         Evaluate[({r Cos[#1], 0, (r)^(1/3) Sin[#1/3]} &) /@ {0, π,2 π, 3 π}],         {r, 0, 2},         PlotStyle -> {{Black, AbsoluteThickness[5]}}]          Show[p1, p2]      ![enter image description here](http://i.stack.imgur.com/d2fCx.jpg) Rectangular coordinates and branches in black               p3 =       ParametricPlot3D[{r Cos[φ], r Sin[φ], r^(1/2) Sin[φ/2]}, {r, 0, 1}, {φ, 0, 4 π},         ColorFunction ->           Function[{x, y, z, r, φ, θ}, {Specularity[#], Glow[#]}& @ Hue[Rescale[φ, {0, 1}]]],         PlotPoints -> {20, 60}, Mesh -> 25]          Show[p3, p2]      ![enter image description here](http://i.stack.imgur.com/Bh4r0.jpg) Polar coordinates with branches in black The square roots are both identical. If I go on the cubic roots, the polar representation is the same with a change from 2 to 3, but I don't know how to modify the rectangular code to generate the same surface. So for example:               p4 =       ParametricPlot3D[{r Cos[φ], r Sin[φ], (r)^(1/3)Sin[φ/3]}, {r, 0, 1}, {φ, 0, 6 π},         ColorFunction ->           Function[{x, y, z, r, φ, θ}, {Specularity[#], Glow[#]}& @ Hue[Rescale[φ, {0, 1}]]],         PlotPoints -> {40, 120},         Mesh -> 25]          p5 =       ParametricPlot3D[         Evaluate[({r Cos[#1], 0, (r)^(1/3) Sin[#1/3]} &) /@ {0, π,2 π, 3 π, 4π, 5π}],         {r, 0, 2},         PlotStyle -> {{Black, AbsoluteThickness[5]}}]          Show[p4, p5]      ![enter image description here](http://i.stack.imgur.com/NVq86.jpg) Cubic root in polar with branches in black I have no idea how to get the same cubic root surface using polar coordinates.


Symbolic solution of system

everyone! I am sorry, but I am an abcolute novice of Mathematica (to be more precise this is my first day of using it) and even after surfing the web and all documents I am not able to solve the following system:               Solve[{y*(((y*x)/(beta*b))^(1/(beta - 1)) - v) - c*alpha ==         0, ((x/alpha))*(((y*x)/(alpha*beta*b))^(1/(beta - 1)) -             v) + (((y*x)/alpha) -             2*alpha*((yx)/(2*beta*b))^(1/(beta - 1)))*(1/(beta -               1))*(x/(alpha*beta*              b))*((y*x)/(alpha*beta*b))^((2 - beta)/(1 - beta)) == 0}, {x,        y}]      What I need is to solve following systems, getting x and y expressed through all these symbols. Is it even possible? Thank you in advance.


Comparing 2 Data Sets in a Single Plot

I have 2 data sets, `data1` and `data2` with large (in the thousands) amounts of data and I want to compare them in a plane. They aren't modeled by the normal distribution, but I'm using that here for simplicity.               data1 = RandomReal[NormalDistribution[], {10000, 2}];     data2 = data1+1;      I can put these on a list plot and plot them. However, this is visually unpleasing and even hides some of the data.               combPlot = ListPlot[{data1, data2},         PlotRange->All,         PlotStyle->PointSize[0.01],         PlotStyle->Directive[Opacity[0.5]]     ];     Export[Directory[] <> "/figures/test-comb.pdf", combPlot];      ![](http://imgur.com/ylFd9.png) The `SmoothDensityHistogram` command with the following color function shows the data exactly how I want it for each data set.               histOpts = {ColorFunction -> Function[c, GrayLevel[1 - c]],         PlotRange -> {{-4, 4}, {-4, 4}}, ImageSize -> Medium};     hist1 = SmoothDensityHistogram[data1, histOpts];     Export[Directory[] <> "/figures/test-hist1.pdf", hist1];     hist2 = SmoothDensityHistogram[data2, histOpts];     Export[Directory[] <> "/figures/test-hist2.pdf", hist2];      ![](http://i.imgur.com/z20jC.png) ![](http://i.imgur.com/vtZSJ.png) How can I combine these into a single plot, preferably with different colors? I had no success using the `Show` command. Again, the idea is to visually compare the 2 data sets. If there are any other alternatives, I'd like to see them too. * * * Update: After seeing Diego Zviovich's post, I was able to get it working for my example. However, my actual data sets may significantly differ so the bounds aren't the same:               data1 = RandomReal[NormalDistribution[], {10000, 2}];     data2 = data1+10;          hist1 = SmoothDensityHistogram[data1,         ColorFunction->Function[c, Hue[215/360, .973, 1, c]],          PlotRange->All, ImageSize -> Medium];     hist2 = SmoothDensityHistogram[data2,          ColorFunction->Function[c, Hue[311/360, .973, 1, c]],          PlotRange->All, ImageSize -> Medium];     combHist = Show[         Rasterize[hist1],         Rasterize[hist2],         PlotRange->All     ];          Export[Directory[] <> "/figures/test-hist1.pdf", hist1];     Export[Directory[] <> "/figures/test-hist2.pdf", hist2];     Export[Directory[] <> "/figures/test-combHist.pdf", combHist];      data1: ![](http://i.imgur.com/Wrtky.png) data2: ![](http://i.stack.imgur.com/qp6Wn.png) Combined: ![](http://i.stack.imgur.com/jgGph.png) ~~How do I correct the bounds for this?~~ * * * Update: Using m_goldberg's suggestion, I'm able to get what I want: ![](http://i.stack.imgur.com/gD1HV.png) I'll leave this opened for a little for any further discussion, but I'm satisfied with this now. Thanks to everyone who helped! * * * Further update (sorry): I'm a little unsatisfied with the results for my actual data. The first one appears fine, but the second is overly distorted: ![](http://i.stack.imgur.com/pD2mv.png) ![](http://i.stack.imgur.com/TF6e9.png) Does anybody have any further suggestions for these?


Automatically wrap abritrary-length text in graphics

**Question:** How to insert `Style`d text of unknown style and length into a graphics and have it wrap at a `Scaled` width? **Attempt:** I found the following two ways to wrap text when I was googling:               (* Based on: http://forums.wolfram.com/mathgroup/archive/2008/Mar/msg00977.html *)     syd[txt_, w_: 100, h_: 50] :=       Graphics[{Inset[Framed@txt, {0, 0}, {0, 0}, {w, h}]}]          (* Based on: http://forums.wolfram.com/mathgroup/archive/2008/Mar/msg00916.html *)     fred[txt_, w_: 150] := Graphics[{        Inset[Framed@Pane[Style[txt, LineIndent -> 0, TextAlignment -> Left], w], {0, 0}]        }]      But I want to handle text of unknown length so I did this to Syds solution:               (* Since {w,h}={100,50} worked for a string of length 460     it's reasonable to assume each character needs (100*50)/460 area units,     so any string should have area of StringLength[txt]*(100*50)/460 \     since w is given let      h=StringLength[txt]*(100*50)/(460*w)     *)     sydGuessHeight[txt_, w_: 100] :=       Graphics[{Inset[         Framed@txt, {0, 0}, {0, 0}, {w,           StringLength[txt]*(100*50)/(460*w)}]},        PlotLabel -> Style["syd guess: w=" <> ToString[w], Red, Bold]]      A test:               txt1 = (StringJoin @@          Table["The quick brown fox jumped over the lazy dog. ", {10}]);     txt2 = (StringJoin @@          Table["The quick brown fox jumped over the lazy dog. ", {20}]);     Grid[Partition[Image /@ {         syd[txt1],         syd[txt2],         syd[txt2, 100, Automatic] ,         fred[txt1],         fred[txt2],         sydGuessHeight[txt2]}, 2]]      ![enter image description here](http://i.stack.imgur.com/YlGmH.png) This is all very inelegant and I still can't use it to wrap text of a `Scaled` width nor can I supply `Style`d text since any modification in font will break the guess.


Extracting Pareto elements from a list

How can I extract the Pareto elements from a list? For example, for that list:               list = {      {"A&W", 15}, {"Bubbly", 19}, {"Aquabona", 42},       {"Lanitis Extra", 91}, {"Ayataka", 80}, {"DASANI Nutriwater", 12},       {"diet Lift/Lift light", 2}, {"Minute Maid Antiox", 74},       {"Bimbo", 40}, {"Minute Maid Deli", 5}, {"Fire", 69}, {"Club",14},       {"Nada", 46}, {"Bu", 46}, {"Aybal", 29}, {"Kin",73},       {"Minute Maid Just 10", 31}, {"Hero", 90}, {"diet Oasis",65}, {"Canada Dry", 30}     }      I want to get this result:               {{"Lanitis Extra",91},{"Hero",90},{"Ayataka",80},{"Minute Maid Antiox",74},      {"Kin",73},{"Fire",69},{"diet Oasis",65},{"Nada",46},{"Bu",46},{"Aquabona",42}}      ![enter image description here](http://i.stack.imgur.com/h2cX8.png) So that these products represent approximately 80% of the total value. The final list can be sorted or not and the real case has 15,000 elements. Make no difference for my purpose that is to tag these products as special ones.


Why might ListStreamPlot fail to cover StreamPoints?

I have a pretty sparse array of vectors (in the colloquial sense that it covers the domain sparsely; it's not a `SparseArray`). `ListStreamPlot` without options was only showing one stream. I'm trying to pass in an array of `StreamPoints` to hit (namely, the points for which vectors are defined), but most still end up not hit: ![sparse StreamPoints failing to hit](http://i.imgur.com/3SOWua6.png) You can see the notebook here: https://dl.dropboxusercontent.com/u/13934821/incomemobility.nb My guess is my vector array (21 vectors from this data on income mobility (pdf link)) is too sparse, and the vector field ends up kind of, um, underspecified? Does that make any sense?


Import a data stored in EXCEL and change it to a Table

I have an EXCEL file in which large amount of numbers is stored in a column in the first sheet, like data in the column A of the sheet1 of excel file. When I apply the Import function; the data is imported into Mathematica like this: {{{1},{2},{3}}}. But I want them to be in form of a one dimensional table or array like: {1, 2, 3}. How is this possible?


Summa package problem

I need to use the features of the Summa package but it doesn't work in _Mathematica_ 9\. It gives the error               Cannot open Utilities`FilterOptions`      My question is: Is there an alternative (more modern) package with similar features, or a way to make `Summa.m` work in _Mathematica_ 9? * * * Following @Nasser I solved it. The problem was that the input of `FilterRules` is in opposite order, e.g.               FilterOptions[Expand,{opts}]      is changed to               Sequence@@FilterRules[{opts},Options@Expand]


Understanding Function and Variable in Mathematica for beginner

I'm reading the book of Leonid Shifrin, and I love the way the book explains the core in `Mathematica`. As everything is an expression, now I understand that, there are no real function or variable in `Mathematica`. Function is such an indexed variable containing several rules.               Head /@ {Sin, Sin[x], x, 3}     AtomQ /@ {Sin, Sin[x], x, 3}     Attributes /@ {Symbol, String, Integer}      > {Symbol, Sin, Symbol, Integer} > > {True, False, True, True} > > {{Locked, Protected}, {Protected}, {Protected}} So both function `Sin` and variable `x` are `Symbol`. Everything in `Mathematica` is Symbol, String, or Number. This principle helps me a lot.               f = Sin;     g = Sin[x];     {f[x], g[x]}      > {Sin[x], Sin[x][x]} Without this principle, a beginner can think that the function `g` equals to the function `Sin[x]`. So `g[x]` should return as `Sin[x]`. And he can think that the definition `f = Sin` is impossible because Sin should be expressed as a function Sin[something]. But here, we can see that `Mathematica` is very flexible. If we consider `Sin` as a variable, so assigning `f = Sin` is totally correct. And `g[x]` is not equal to `Sin[x]`, but `Sin[x][x]`. I think this is a very basic thing, that a beginner should remember. So many books on `Mathematica` don't explain these principles, they just teach how to use the command. But understanding the core in Mathematica for me is much more important, because it is the basic to master `Mathematica` programming style. Thank you Leonid Shifrin. As now, I see that functions and variable are `Symbol`. Beside `Symbol`, could we use another type as a variable? For example, I would like to have a list of 40 variables a1=1, a2=2, a3=3,... a40=40. But I don't want to use indexed variable `a[1]`, `a[2]`, `a[3]`, `a[40]` because for me, it is just one variable `a` with several index. Of course, the natural way is typing `a1 = 1`, `a2 = 2`, ... `a40 = 40` manually. But how to do it in automatically in a loop or table way? My first try is to generate `"a1"`, `"a2"`, ... `"a40"` as `String`.               "a" <> # & /@ ToString /@ Table[i, {i, 3}]      > >     {"a1", "a2", "a3"} >   But `String` can not be used as variable....               {"a1", "a2", "a3"} = {1, 2, 3}      > Set::setraw: Cannot assign to raw object a1. >> So how to generate a list of variable? a1, a2, a3...? I try to use `ToExpression` to convert the String to Expression, I got a list of variable a1,a2,a3.               ToExpression["a" <> # & /@ ToString /@ Table[i, {i, 3}]]      > {a1, a2, a3} I'm trying to assign the value: (*)               ToExpression["a" <> # & /@ ToString /@ Table[i, {i, 3}]]] = {1, 2, 3}      > Set::write: Tag ToExpression in ToExpression[{a1,a2,a3}] is Protected. > >> > What is wrong here. I try to add Evaluate on the l.h.s:               Evaluate@ToExpression[        "a" <> # & /@ ToString /@ Table[i, {i, 3}]] = {1, 2, 3}     {a1, a2, a3}      > {1, 2, 3} Finally, it works. But are there any another way than this way (too long) to generate a list of variable `a1`, `a2`, `a40`? and why I need to `Evaluate` the l.h.s at (*) before `Set` to {1,2,3} ? Edit: Thanks to @RunnyKine, now I understand why I must `Evaluate` at (*) before using `Set`. > "because when using Set, Mathematica evaluates the R.H.S. and leaves the > L.H.S. unevaluated."


Hungarian Algorithm using BipartiteMatchingAndCover Function

I have a bipartite graph with two sets of vertices.               Needs["Combinatorica`"]     g = CompleteGraph[3, 3];     edgeWeights = {{53, 96, 37}, {47, 87, 41}, {60, 92, 36}};     g1 = SetEdgeWeights[g, Flatten[edgeWeights]];      I want to find the optimal assignment that minimizes the total cost (sum of assigned edges). For this I use:               BipartiteMatchingAndCover[g1]      The answer I get is {{1, 5}, {2, 6}, {3, 4}}, which tells me that vertex 1 is assigned to vertex 5, 2 is assigned to 6 and 3 is assigned to 4. These assignments correspond to a total cost of 96+41+60 = 197. I would have expected the answer to be {{1,6},{2,4},{3,5}} which corresponds to a total cost of 37+47+92=176. It seems like the function is finding the assignments associated with the maximum cost instead of the minimum cost. I tried using `1/edgeWeights` as edge weights, but got the same result. Any ideas?


Using sublists returned from a function as elements of a list argument to an other function

This is a contrived example, but it gets the point across. I am looking to use the following as inputs:               a = {10, 11};     b = {5, 7};     MakeCD[x_] := {{x, 2 x}, {3 x, 4 x}};      to function that takes a list of sublists. `ListPlot` is a suitable example of the function. Using `1` as the argument to `MakeCD`, `MakeCD` returns: `{{1, 2}, {3, 4}}` I am looking to supply `{{10, 11}, {5, 7}, {1, 2}, {3, 4}}` to `ListPlot` I can achieve this with the following:               {c, d} = MakeCD[1];     {a, b, c, d}      Also with:               Join[{a}, {b}, MakeCD[1]]      I am sure there is a better way to do this, but I have not yet stumbled upon it yet.


ListPlot, PlotMarker -> y value

at first sorry if this question is already answered. I would like to display y value as plot marker in listplot               ll = {{33, 11, 2}, {3, 5, 4}, {6, 4, 8}}     Table[ListLinePlot[ll[[i, 1 ;; 3]], PlotLabel -> i,        PlotMarkers -> valueY], {i, 3}]      Gives me output like this: ![output from code](http://i.stack.imgur.com/qlZM9.png) and I'd like to have 33, 11, 2 instead of valueY. Thanks in advance.


Marking specific points on a 3D curve

Here is the curve below. (written as a position vector)               r = {Cos[7 Pi*t], Cos[6.2*Pi*t], 2.5*t}     ParametricPlot3D[r, {t, 0, 2}]      I want to know how I can mark specific points on this curve, for example when `t = 0` and `t=1`. I would also like to label those points.


Sorting a list and finding an array of indices that sorts the list

How can I sort a list and also get a list of indices that sort this list? For example: primary list is a               a={1,4,6,7,0,2};      sorted list is b               b={7,6,4,2,1,0}      and also return list c               c={4,3,2,6,1,5}


Code performance problem

Could anyone help me with the attached code? How would you speed up my attached code in some degree? Your comments are highly welcome.               ClearAll["Global`*"];     α = 0.95; k = 1000; M = 25000;          t0 = 0; tf = 25; h = (tf - t0)/M;          g1[t_] := 0.55;          x1[i_ /; -k <= i <= 0] := g1[t];          t[j_] := j*h          alfa = 0.75;          f1[t_, u_, v_] := u - u*u*u - alfa*v          x1[j1_] := x1[j1] =         g1[0] + (h^α/Gamma[α + 2])*          f1[t[j1],            g1[0] + (1/Gamma[α])*             Sum[(h^α/α)*((j1 - 1 + 1 - j)^α - (j1 -                     1 - j)^α)*                          f1[t[j], x1[j], x1[j - k]], {j, 0, j1 - 1}],            x1[j1 - k]] + (h^α/Gamma[α + 2])*               Sum[Which[             j == 0, (j1 - 1)^(α + 1) - (j1 -                  1 - α)*(j1 - 1 + 1)^α,              1 <= j <= j1 -            1, (j1 - 1 - j + 2)^(α + 1) + (j1 - 1 -              j)^(α + 1) -                     2*(j1 - 1 - j + 1)^(α + 1), True, 1]*        f1[t[j], x1[j], x1[j - k]], {j, 0, j1 - 1}];           ListLinePlot[Table[{t[n], x1[n]}, {n, 0, 25000}]]


How do I slice an image of size "width × height" in n² pieces of size "width / n × height / n"?

Background: What I want is to make a jigsaw from an image. (A simple one where the pieces are polygons.) I have the following strategy in mind. Create a set of polygons and assign images (or just the original image) to them as a texture and set the texture coordinates. I know from the documentation (Lena example) how to use an image as a texture. Is chopping up the image in parts and assign these parts as textures a feasible strategy? If so, then I have the following question: **Question: Given an image of size width × height, how do I slice it in n² pieces of size width / n × height / n ?**


Removing commented lines of text in a string

Suppose that I have a string `str`. `str` contains headings -- which are written in commented lines -- and data. For example:               str = "# Heading 1     # Heading 2     @ Heading 3     @ Heading 4     Data 1     Data 2     Data 3";      where `#` and `@` denote commented lines. Now, I would like to write a function `removeComments` to remove all lines in `str` that are commented. That is, I would like to remove all lines in `str` that start with the character `#` or the character `@`. I have come up with one way to do this, I think. My procedure is to first split `str` into lines using `StringSplit` with the `"\n"` delimiter; then use `DeleteCases` to delete all lines in that list which begin with either `#` or `@`; and, finally, convert the list back to a string using `Riffle` and `StringJoin`. So, I have the following:               removeComments[str_String] := Module[{result},       result = StringSplit[str, "\n"];       result =         DeleteCases[         result, _?(StringMatchQ[#, ("#" ~~ ___) | ("@" ~~ ___)] &)];       result = StringJoin[Riffle[result, "\n"]];       result       ]     removeComments[str]      which gives the following _correct_ output (a string):               Data 1     Data 2     Data 3      _However_ , now suppose that one of my data items (for example, a single space in front of `Data 2`) has one or more leading spaces:               str = "# Heading 1     # Heading 2     @ Heading 3     @ Heading 4     Data 1      Data 2     Data 3";          removeComments[str]      In this case, I get the **_incorrect_** output:               Data 1     Data 3      That is, `Data 2` is omitted altogether. Something is clearly wrong with my approach, but I haven't been able to find my mistake (although it is probably obvious). Could you please help me find what is wrong? Thanks for your time.


Proper localization of variable names

In functions like `NonlinearModelFit` I need to specify parameters with a symbol name. If I localize these parameters they get cluttered in the output (e.g.`"ParameterTable"`):               {a, b, c, d} = {2, 30, 4, 0};     data = a PDF[NormalDistribution[b, c], Range@100] +         RandomReal[{-.01, .01}, 100];          fitFunc[a_, b_, c_, d_, x_] := a PDF[NormalDistribution[b, c], x] + d          fit[data_] := Module[{a, b, c, d, aStart, nlmf},       aStart = Max@data;       nlmf = NonlinearModelFit[data,          fitFunc[a, b, c, d, x], {{a, aStart}, {b, 30}, {c, 4}, {d, 0}}, x];       nlmf["ParameterTable"]       ]          fit@data      How can I avoid outputs like `a$18554` in the the ParameterTable without using global symbol names for the parameters a, b, c, d inside `NonlinearModelFit`?


Efficient way of setting up a rule

I tried to define a simple rule defining how λ acts on `ψ[n]`:               myrule1 = λ ψ[n_] -> α[n + 1]  ψ[n + 1];      The result I get is correct provided there's just one λ on the RHS of `ψ[n]`. For instance:               λ^2  ψ[n] //. myrule1      isn't computed at all. On the other hand, if I do it step by step:               λ α[1 + n] ψ[1 + n] /. myrule1      I get the correct result. I tried to define a new rule:               myrule2 = λ^m_ ψ[n_] -> α[n + 1] λ^(m - 1) ψ[n + 1];      but it doesn't work. Since the recursive method seemed to work, I created a function which multiplies `ψ[m]` by λ `n` times:               timesλ[n_] := Nest[Times[λ, #] /. myrule1 &, ψ[m], n] &      But this is a very crude way of solving this problem. Do you have any other ideas?