title: Measure length and diameter of objects in an image

text: I am new to _Mathematica_ , and I am trying measure length and diameter of rectangular objects in an image. I wanted to fit rectangles in the objects, and then get the values. Can I do that with `ComponentMeasurements`? how does the {"Rectangle"} command work? How can I set aspect ratio, or verticality selection rules? or other types conditions to rectangle fit? What I did so far is as follow:               image = Import["http://i.stack.imgur.com/5WGzV.jpg"]      ![image of some objects](http://i.stack.imgur.com/5WGzV.jpg)               imageNS = ImageCrop[image, {1024, 650}, Bottom]      so far I just removed the bar at the bottom.               imageA = ImageMultiply[imageNS, 2.8] // ImageAdjust;     imageB = MeanShiftFilter[imageA, 5, 0.03, MaxIterations -> 20] // ImageAdjust;      in this way I have enhanced the contrast of the image.               binaB = MorphologicalBinarize[imageB, {0.4, 0.7}];      Then I binarize the image. since in the binarized image there is no bottom line for the "trees", I try to find it as follows:               imageR = RidgeFilter[imageB, 1.5] // ImageAdjust;     binaE = MorphologicalBinarize[imageR, {0.075, 0.7}];     a = EdgeDetect[binaE, "StraightEdges" -> 0.55];     b = Closing[a, 6];     c = GradientFilter[b, {{1, 100}, 10}];     d = Binarize[ColorNegate[Dilation[c, {{1}, {1}, {1}, {1}, {1}}]]];     ebin = Closing[ImageMultiply[binaB, d], 1]      Now I have the bottom line of the trees, although the problem is that morphologically the trees still belong to the same domain, they are all "connected". This makes the problem more complicated since ComponentMeasurements[ebin,"BoundingBox"] fit bigger rectangles that groups bunches of trees... Any idea how to fit these rectangles into the trees? I have tried a different approach to get at least the length of these structures.I use a derivative filter and horizontal erosion to get the top of the structures. Then I get the position of the top of the strcuture with Pixelvalue positoin, get the y coordinate, and subtract it to the bottom line.               qr = Binarize[Erosion[DerivativeFilter[ebin, {1, 0}], {{1, 1, 1, 1}}]]      get the max points positions               ebinm = PixelValuePositions[qr, "Max"];     ebinmy = Table[ebinm[[i]][[2]], {i, 1, Length[ebinm]}];      sum the raws of the matrix to get the baseline               ebinmm = Total[ImageData[qr], {2}];      get the baseline position               baseline = Position[ebinmm, Max[ebinmm]] [[1]][[1]];      get the length of the nws by doing the difference between               lenghts = Subtract[baseline, ebinmy];     Histogram[lenghts]      Still, how do I get the diameters? I found a nice approach in: Image processing: Floor plan - detecting rooms' borders (area) and room names' texts I tried to implement it as follows:               distTransform = DistanceTransform[ebin] // ImageAdjust;     centerAreas = ImageDifference[GeodesicDilation[distTransform, ebin],distTransform];     watershed = ImageMultiply[Dilation[WatershedComponents[centerAreas] // Image,{{1},{1}}],ColorNegate[qr]]     rooms = ComponentMeasurements[watershed, "BoundingBox"];      Although the fact that the trees are not individually morphologically defined gives me troubles, and no rectangles are fit into it.This is what I get: ![enter image description here](http://i.stack.imgur.com/h9hbs.jpg) Anybody able to fit rectangles into it? Cheers!


title: ListContourPlot is blocking my geometry

text: I have a Navier-Stokes solution for a flow past a cylinder. I have attached the DAT file. The columns in the DAT file contain the x,y,u,v,p data, respectively. The DAT file can be obtained from our attachment repository here. I am trying to make _Mathematica_ plot a contour plot that looks like this for velocity and pressure ![Velocity field](http://i.stack.imgur.com/1d2RN.png) ![Pressure](http://i.stack.imgur.com/4S2Qd.png) But when I use the following to plot my u,v,p fields, the contours erase my geometry. This is what I have done so far:               Data = Import[        "https://raw.github.com/stackmma/Attachments/master/data_2571_187.txt",        "Table", "IgnoreEmptyLines" -> True];     x = Data[[All, 1]];     y = Data[[All, 2]];     u = Data[[All, 3]];     v = Data[[All, 4]];     p =  Data[[All, 5]];     gridsolution = Transpose[{x, y}];     velocityu = Transpose[{x, y, u}];     velocityv = Transpose[{x, y, v}];     pressure = Transpose[{x, y, p}];     ListContourPlot[velocityu, PlotRange -> All, Contours -> 99,      ContourStyle -> {None}, ColorFunction -> "Rainbow",      PlotLegends -> Automatic, PlotLabel -> "u(x,y)",      AxesLabel -> {"x", "y"}]     ListContourPlot[velocityv, PlotRange -> All, Contours -> 99,      ContourStyle -> {None}, ColorFunction -> "Rainbow",      PlotLegends -> Automatic, PlotLabel -> "v(x,y)",      AxesLabel -> {"x", "y"}]     ListContourPlot[pressure, PlotRange -> All, Contours -> 99,      ContourStyle -> {None}, ColorFunction -> "Rainbow",      PlotLegends -> Automatic, PlotLabel -> "P(x,y)",      AxesLabel -> {"x", "y"} ]      This results in the following figures: ![u](http://i.stack.imgur.com/LapnS.png) ![v](http://i.stack.imgur.com/IoeIS.png) ![pressure](http://i.stack.imgur.com/8ibqX.png) How can I make my velocity and pressure plot look like the COMSOL plots above? _Mathematica_ doesn't understand that there is a cylinder in the middle, but just overwrites the geometry with contours.


title: Error in CUDALink installation? SystemInformation[] does not report version number

text: I am using Mathematica 9.0.1.0 for linux, on Crunchbang "Waldorf" (Debian 7). Video card is nVidia NVS 3100m. CUDA version is 5.5, and video drivers are 331.49 as installed by smxi. My issue is that there appear to be some errors in comparison to the documentation, my video card drivers contain spurious text and the CUDA version is absent. CUDAQ[] responds "TRUE" and CUDAResourcesInformation[] returns a bunch of data, but I am having the same issues as the CUDALink is not initialized topic. I am unsure if the errors in my SystemInformation[] are related to my lack of CUDALink functionality or if it's a problem of card age.. Has anyone seen this before? Can anyone help? I went through a lot to try and get everything working..![SystemInfo Error](http://i.stack.imgur.com/Jyq1G.png)


title: Soft-Match String Comparison

text: I have a list of names in which I would like to check for duplicates. However, within the list, the duplicates may not show up as exact duplicates of each other - for instance, `{Barack Obama, Barack H. Obama, Barack Hussein Obama, Obama Barack Hussein}` are all considered likely candidates to be duplicates of each other. Furthermore, the data may contain slight mistakes - for instance, the following and other variants would be considered (near) duplicates too. `{Barack Obama, barack Obama, Barrack Obama}` What I would like to do is to automatically **highlight** these duplicates _(for example, by changing their font size or color as displayed on screen)_ so that I can later go through the list manually and confirm whether or not the duplicates are indeed duplicates. My current approach is as such:               nlsplit =      StringSplit /@ namelist; (*splitting the names at the whitespace*)     nlsplitsort =      Map[Sort, nlsplit,      2] ; (*sorting the names of each person alphabetically - for     example, John Anderson Doe becomes {Anderson, Doe, John}*)     nlsplitsortpad = Transpose[Map[PadRight[#, 5] &, nlsplitsort, 2]][[1]];     (*pad each person's name with zeros so that Mathematica doesn't sort     based on list length but on name*)     Sort[nlsplitsortpad]      This question may be linked to mine, but I feel it's sufficiently different to merit a post. Mr Wizard also informed me that a question of Soft-Match String Comparison may have been asked before and the link is here as Sjoerd C. de Vries points out. **Edit** : It would be great if the following could be done, but from my knowledge of Mathematica, I'm not sure whether it's worth the effort.   1. The process of highlighting duplicates does not change the ordering of the original list, but simply highlights them, and    2. I could simply hover over a duplicate candidate where using `Tooltip` we display the possible matches identified as similar to this duplicate candidate.   3. By choosing from a list of options I could do one of the following:      * select the current duplicate candidate as the entry I want to keep (and remove all other similar candidates from the main list)     * skip to one of the other matches displayed by the `Tooltip` and choose that as the entry I want to keep (removing all other similar candidates from the main list)     * confirm that the current candidate is not in fact a duplicate, and remove it from the list of any candidate of duplicates.


title: Invariant error plot for an arbitray system of ODE

text: i try to use `InvariantErrorPlot` command for a generic system of ODE but i find only example with pre-building equations from Mathematica Packages. This is one of them:               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];     system = GetNDSolveProblem["PerturbedKepler"]     vars = system["DependentVariables"]     H = system["Invariants"]     time = {T, 0, 290};     step = 1/25;     Met = {"SymplecticPartitionedRungeKutta", "DifferenceOrder" -> 10,         "PositionVariables" -> {Subscript[Y, 1][T], Subscript[Y, 2][T]}};     sol = NDSolve[system, time, Method -> Met, StartingStepSize -> step,         MaxSteps -> Infinity];     ParametricPlot[      Evaluate[{Subscript[Y, 1][T], Subscript[Y, 2][T]} /. sol],       Evaluate[time]]     InvariantErrorPlot[H, vars, T, sol, PlotStyle -> {Blue, Red}]       Now the question is simple: can I modify it to use `InvariantErrorPlot` for my equations? And if so, how? Thanks a lot.


title: Does a manipulation of a plot area produce new data?

text: You do a ListPlot.               Plot[Sin[x^2], {x, 0, 1}]       pdat1 = With[{fig = Plot[Sin[x^2], {x, 0, 1}]},        First@Cases[fig, Line[x_] :> x, Infinity]];        ![fig 1](http://i.stack.imgur.com/8CSkq.jpg)   ![fig 2](http://i.stack.imgur.com/GapgK.jpg)   ![fig 3](http://i.stack.imgur.com/XUpUH.jpg)   ![fig 4](http://i.stack.imgur.com/q6TH4.jpg)   ![fig 5](http://i.stack.imgur.com/z2jc9.jpg)   ![fig 6](http://i.stack.imgur.com/N68Jd.jpg) You get your diagram. fig 1.   You select the ListPlot area.   A red fram shows.   A tooltip says: Double-click to edit. fig 2.   You Double-click the plot line.   Another red fram shows. fig 3.   You again Double-click the plot line.   The data points become visible. fig 4.   You take a handle to resize a data point. fig 5.   You deselect the Plot. fig 6. There are now some new values constitute the diagram.   Question is:   How can you list/table the plot diagram values after this manipulation?


title: Exporting a list as RawData or Data

text: My problem is quite simple yet I do not seem to figure out the solution to it. I am simply trying to export a list in _Mathematica_ , actually a list of lists of lists etc, something like `{{...,{...}},{...}}`, but the `Head` is a list. I want to export this as raw _Mathematica_ symbols so that I can access it later. Lets take a simple list, say               list = {1,a,Pi};      I am trying:               Export["listname",list,"RawData"]       and also               Export["listname",list,"Data"]      but getting the following error: > >     Export::infer: Cannot infer format of file listname. >> >   This works for other formats such as `CSV` or `TXT`.


title: Why doesn't repeated PatternSequence work with explicit pattern names?

text: Why would this work:               Clear[f]     f[a : PatternSequence[b_, c_]] := {a};     f[1, 2]     (* {1, 2} *)      and this also works:               Clear[f]     f[a : PatternSequence[_, _] ..] := {a};     f[1, 2, 3, 4]     (* {1, 2, 3, 4} *)      but this does not work?               Clear[f]     f[a : PatternSequence[b_, c_] ..] := {a};     f[1, 2, 3, 4]     (* f[1, 2, 3, 4] *)      * * * **Edit** : Now that @RunnyKine's answer and @kguler's comment have perfectly answered my original question, I have another related question: is there a pattern-based way that I could extract the first element of the repeated pattern sequence without doing this?               Clear[fNew]     fNew[a : PatternSequence[_, _] ..] := Partition[{a}, 2][[All, 1]]     fNew[1, 2, 3, 4]     (* {1, 3} *)


title: How to plot inequalities taking into account that points must be integers and not reals?

text: I have solved with Mathematica 9 the following integer inequalities using Reduce:               eq = Reduce[       m (k - 1) + (k - 2) == c k && m >= 2 && k >= 2 && c >= 1, {k, m,         c}, Integers, Backsubstitution -> True]          (* (k | m | c) \[Element] Integers && k >= 2 && m >= 2 &&       c == (-2 + k - m + k m)/k *)          better = Reduce[       m (k - 1) + (k - 2) <  c k && m >= 2 &&  k >= 2 && c >= 1, {k, m,         c}, Integers, Backsubstitution -> True]          (* (c \[Element] Integers && k == 2 && m == 2 &&         c >= 2) || ((m | c) \[Element] Integers && k == 2 && m >= 3 &&         c > m/2) || ((k | m | c) \[Element] Integers && k >= 3 && m >= 2 &&         c > (-2 + k - m + k m)/k) *)          worst = Reduce[       m (k - 1) + (k - 2) >  c k && m >= 2 &&  k >= 2 && c >= 1 , {k, m,         c}, Integers, Backsubstitution -> True]          (* ((m | c) \[Element] Integers && k == 2 && m >= 3 &&         1 <= c < m/2) || ((k | m | c) \[Element] Integers && k >= 3 &&         m >= 2 && 1 <= c < (-2 + k - m + k m)/k) *)      Now I need to plot them. However, using `RegionPlot3D` I can only plot a region made of reals, while the solutions are integers. What is the proper way to plot the solutions when the domain is `Integers` ?


title: How do I solve this probability problem with Probability？

text: > Consider a stick of length 1. Pick two points uniformly at random on the > stick, and break the stick at those points. What is the probability that the > three segments obtained in this way form a triangle? I have implemented two versions. Version 1 works correctly, but version 2 doesn't, How can I fix the second version? version 1               Module[{min,  max},        {min, max} = {Min@#, Max@#} & /@ RandomReal[1, {10^5, 2}] // Transpose;       Mean@MapThread[         Function[{x, y, z}, N@Boole[x + y > z && x + z > y && y + z > x]],          {min, max - min, 1 - max}]]      version 2               Block[{t1, t2, t3},       t1 = {x > 0, y > 0, x + y < 1};       t2 = {x + y > z, x + z > y, y + z > x} /. z -> 1 - x - y;       Print[t3 = And @@ t1 ~ Join ~ t2 // FullSimplify];       Probability[t3,          Distributed[x,  UniformDistribution[{0, 1}]] &&          Distributed[y,  UniformDistribution[{0, 1}]]]]


title: List of Coefficients of Expression with symbolic Terms

text: (I am affraid that this is a duplicate, but I read several already asked questions and non of them helped me. If it's already answered, please tell me) I have expressions like this               expr1=F1[0]*F2[3]*F3[2]+4I*F1[1]*F2[2]*F3[1]-2*F1[0]*F2[-2]*F3[2]     expr2=4*F1[0]*F2[2]*F3[1]-I*F1[1]*F2[0]*F3[-1]-1*F1[1]*F2[0]*F3[2]+2*F1[6]*F2[1]*F3[1]      in general the expression is always of this form               expr= c1*F1[z1]*F2[z2]*F3[z3]+c2*F1[z4]*F2[z5]*F3[z6]+c3*F1[z7]*F2[z8]*F3[z9] + ...      with c1,c2,c3 complex, and z1-z9 integers, and there can be arbitrary many F1*F2*F3-terms. Now I want to find the coefficients of this expressions. I tried               CoefficientList[expr, F2[__]*F3[__]*F4[__]]      but it didnt give any result. Now I found a semi-solutions (which works if all z>=0; by mapping each function call to a prime-power thus they are unambiguous):               exprnew = expr /. {F2[v2_] -> x^(2*v2), F3[v3_] -> x^(3*v3), F4[v4_] -> x^(5*v4)}     CoefficientList[exprnew, x]      **Best-Case:** I want               CoefList[expr] -> {c1,c2,c3}     CoefList[expr1] -> {1,4I,-2}     CoefList[expr2] -> {4,-I,-1,+2}      Thanks for help!!


title: Rasterizing a plot make axes ticks invisible

text: I've evaluated this code:               plot = Plot[x, {x, 0, 10}];     g = Rasterize[plot, ImageResolution -> 300];      Everything looks good except the ticks (on the axes); they are invisible! It seems that _Mathematica_ draws ticks in a default size on the scaled image, and after the image is scaled down, they are made too small to be distinguished at all. The more `ImageResoltion` I specify, the smaller the ticks are and the less pleasing the image is. How can I get the axes ticks to look right?


title: Fraction Alignment in Plot Export to JPG

text: I've produced some plots that have fractional tick labels on the horizontal axis and they look fine.               Plot[Sin[x], {x, 0, 2 Pi},       Ticks -> {Range[0, 2 Pi, Pi/6], {-1, 0, 1}}]      ![enter image description here](http://i.stack.imgur.com/O8OI5.png) However, when I export the plot with               Export["Graph2.jpg",drag graph picture here, ImageResolution->300]       the fraction alignment goes off. ![enter image description here](http://i.stack.imgur.com/OtFaW.jpg) Is there a way to keep the fraction alignment the same in a `jpg`?


title: mathematica 9.0 starts with 2 kernels that take up 2 licenses

text: Mathematica 9 starts automatically with 2 MathKernels which in itself is ok but they also count as 2 licenses and that is definitely not OK. It halves our available concurrent network licenses. Is there an option to prevent this ? Ben Polman


title: Manipulate fails with f[x]=x^k/(1+x^k)

text: I have this code:               Clear[f]     f = Function[x, x^k/(1 + x^k)];     Manipulate[Plot[f[x], {x, 0, 5}], {k, 1, 10}]      But nothing draws as I move the slider. Am I missing something?


title: How to prove that all zeros of the complex polynomial $P(z)$ lie in the closed unit disk $|z| \leqslant 1$?

text: I want to know how to prove that all zeros of the polynomial $P(z)$ lie in the closed unit disk $|z| \leqslant 1$. Where $$P(z)=z^{n+1}+\frac{2(n+1)\cos\alpha}{n+2}z^{n}+\frac{n}{n+2}z^{n-1}+\frac{2 e^{-i \theta}}{n+2}z +\frac{2e^{-i \theta}\cos\alpha}{ n+2}$$ $n\geqslant 1,\pi/2 \leqslant\alpha < \pi,\theta\in \mathbb{R}$.


title: Is it possible to Compile the function with string argument?

text: As we can see from the `Compile` documentation, the typical arguments for `Compile` should be `Integer`, `Real`, `Complex` and `True` | `False`: ![enter image description here](http://i.stack.imgur.com/4dBA6.png) Is it possible to use a `String` as argument type for `Compile`? May be somebody knows a tricky way? I met with task to read the data remotely from oscilloscope and it can send it just as huge, long strings. So I need convert it after to numerical form. It is not a problem but it needs a lot of time if that string contains 5-6 thousands of chars.


title: How can I suppress message "... cannot be used as function"?

text: I'd really appreciate your help. The code gives me a solution, but in the end it says it cannot be used as function, which is not true. Script:               SolveLDE[{x0_, y0_}, {x1_, y1_}] := (     ClearAll[C1, C2, a, b, c, d];     x[t_] = C1 Exp[-2 t] + C2 Exp[4 t];     y[t_] = -3 C1 Exp[-2 t] + C2 Exp[4 t];     Example1 = Solve[x[x0] == x1 && y[y0] == y1, {C1, C2}];     C1 = C1 /. Example1[[1, 1]];     C2 = C2 /. Example1[[1, 2]];     \[Lambda] = {-2, 4};     A = {{a, b}, {c, d}};     X = {x[x0], y[x0]};     dX = {x'[x0], y'[x0]};     EquSys =       Solve[dX == A.X &&           y[y0] == 1/b (x'[x0] - a x[x0]) && #^2 - Tr[A] # + Det[A] ==            0 & /@ \[Lambda], {a, b, c, d}];     {{a, b, c, d}} = {a, b, c, d} /. EquSys;     res = DSolve[{x'[t] == a x[t] + b y[t], y'[t] == c x[t] + d y[t],         x[x0] == x1, y[y0] == y1}, {x[t], y[t]}, t]     )     SolveLDE[{0, 0}, {0, 1}]      As solution i get...               DSolve::dsfun: -(1/4) E^(-2 t)+E^(4 t)/4 cannot be used as a function. >>     DSolve[{E^(-2 t)/2 + E^(4 t) ==       5/2 (-(1/4) E^(-2 t) + E^(4 t)/4) +       3/2 ((3 E^(-2 t))/4 + E^(4 t)/4), -(3/2) E^(-2 t) + E^(4 t) ==       1/2 (-(3/4) E^(-2 t) - E^(4 t)/4) +       9/2 (-(1/4) E^(-2 t) + E^(4 t)/4), True,      True}, {-(1/4) E^(-2 t) + E^(4 t)/4, (3 E^(-2 t))/4 + E^(4 t)/4}, t]      As you can see - the solution is in the bracket....


title: How to Nest a Function with three Arguments?

text: I have two functions with three arguments $f_x(a,b,t)$ and $f_y(a,b,t)$. And i need a nesting like this               fx[A,B,0] (*First step*)     fx[fx[A,B,dt],fy[A,B,dt],0] (*Second step*)     fx[fx[fx[A,B,dt],fy[A,B,dt],dt],fy[fx[A,B,dt],fy[A,B,dt],dt],0] (*Third step*)      Thus, with every step, $A$ is replaced by $f_x(A,B,dt)$ and $B$ by $f_y(A,B,dt)$. How can I implement this in Mathematica?


title: Using compiled function inside NMinimize

text: Consider this code:               variable = Sin[x];     fun = Compile[{{x, _Real}}, variable, CompilationOptions -> {"InlineExternalDefinitions" -> True}];     NMinimize[fun[x], {x}]      This code returns:                CompiledFunction::cfsa: Argument x at position 1 should be a machine-size real number. >>      {-1., {x -> -1.5707963267948966}}      Why do I get the error? How can I resolve this issue? Edit What if we use instead of Sin an expression like a+b? Because in reality I have an expression with 63 variable which must be find by NMinimize I cannot define a function of that expression and use it instead of Sin


title: How to fit exponential function which is not converging

text: I performed an experiment where I measured diffusion in a lipid bilayer. I performed the measurement by fluorescently labeling some molecules in the bilayer, and the irradiating them with light until they become nonfluorescent (bleached). This results in a dark spot in the field of view which gradually regains fluorescence as time progresses. The data here represents the normalized fluorescence recovery. at t = 0 we have no recovery so the value is zero. As time progresses the fluorescence recovery increases until about 70% of the initial value. I am trying to fit the following two functions to my data. However they are not converging. For fitequation1, I can get convergence if I specify constraints. For fit equation2 I cannon get convergence. Any suggestions?               normalized = {0., 0.136813, 0.260859, 0.426885, 0.469779, 0.505445, 0.543104, \     0.566412, 0.579988, 0.595328, 0.617525, 0.644393, 0.647385, 0.665809, \     0.670076, 0.673314, 0.675727, 0.665924}          fitEquation = a (1 - Exp[-b t]) + c (1 - Exp[-d t]);     fitEquation2 = y0 + a (1 - Exp[-k t]);          soln = FindFit[     normalized, {fitEquation, {a > 0 , b > 0, c > 0, d > 0, a <= 1,      b <= 1, c <= 1 }}, {a, b, c, d}, t]      soln2 = FindFit[     normalized, {fitEquation2 , {y0 + a < 1,  k <= 1}}, {y0, a, k}, t]


title: Manipulating a piecewise function

text: A while ago I posted a question regarding differential equations. It was supposed to model heat transfer. We've refined our model a bit (using numerical methods now). Our code now looks like this:                   Manipulate[          tijd = (h*3600 + m*60 + s);          T0 = (T0max + T0min)/2 + ((T0max - T0min)/2)*             Sin[(2*\[Pi]/86400) (t + tijd - 86400/4)];          Sol = NDSolve[{Ta'[t] == -(2*ka + k0)*Ta[t] + ka*Tb[t] + ka*Tc[t] +                k0*T0 + f,              Tb'[t] == kb*Ta[t] - (2*kb + k0)*Tb[t] + kb*Tc[t] + k0*T0,              Tc'[t] == kc*Ta[t] + kc*Tb[t] - (2*kc + k0)*Tc[t] + k0*T0,              Ta[0] == Ta0, Tb[0] == Tb0, Tc[0] == Tc0}, {Ta, Tb, Tc}, {t, 0,              tmax}, MaxSteps -> 100000];          Plot[{Evaluate[{Ta[t], Tb[t], Tc[t]} /. Sol], T0}, {t, 0, tmax},            PlotRange -> {{0, tmax}, {Tmin, Tmax}}, Frame -> True,            Axes -> False,            LabelStyle -> {FontFamily -> "Arial", FontSize -> 12},            FrameLabel -> {"Time (s)", "Temperature (\[Degree]C)"},            ImageSize -> Large],           Style["Initial Temperature", 12, Bold], {{Ta0, 20, "Ta"}, 0,            50}, {{Tb0, 30, "Tb"}, 0, 50}, {{Tc0, 20, "Tc"}, 0,            50}, {{T00, 25, "T0"}, 0, 50}, Delimiter,           Style["k-values", 12, Bold], {{ka, 0.000305, "ka"}, 0,            0.001}, {{kb, 0.00061, "kb"}, 0, 0.001}, {{kc, 0.00061, "kc"}, 0,            0.001}, {{k0, 0.0001525, "k0"}, 0, 0.001}, Delimiter,           Style["Axis values", 12, Bold], {{tmax, 5000, "tmax"}, 0,            86400}, {{Tmin, 15, "Tmin"}, -10, 40}, {{Tmax, 35, "Tmin"}, 0,            100}, Delimiter,           Style["Heat Source", 12, Bold], {f, 0.002,            ControlType -> InputField}, Delimiter,           Style["Time", 12, Bold], {{h, 12, "hours"}, 0,            23}, {{m, 0, "minutes"}, 0, 59}, {{s, 0, "seconds"}, 0,            59}, Delimiter,           Style["Outer temperature", 12, Bold], {{T0max, 25, "Tmax"}, -50,                    50}, {{T0min, 15, "Tmin"}, -50, 50}]         The part I'd like to talk about is this:                   Style["Heat Source", 12, Bold], {f, 0.002,            ControlType -> InputField}      Right now, our heat source is a constant 0.002. What we would like to do, is make it dependant upon the room temperature, so that it shuts off when the room temperature is above say, 18 degrees (we're using celsius). I know this should be possible using                   Piecewise[{0.002, Ta < 18}, 0]      But whenever I insert this into the code as follows, I get errors.                   Style["Heat Source", 12, Bold], {f, Piecewise[{0.002, Ta < 18}, 0],            ControlType -> InputField}      How should I implement this to get the desired outcome? Thanks in advance.


title: Export Messing Up Alignment of Bar Chart

text: Here is my code:               ClearAll["Global`*"]          f = OpenRead["****"]     data1 = ReadList[f, {Number, Number}]     a = BarChart[Last[#] & /@ data1, ChartLabels -> (First[#] & /@ data1),     TicksStyle -> {Directive[0.1      , Opacity[0], FontOpacity -> 1],      Directive[12, Opacity[1], FontOpacity -> 1]},     BarSpacing -> Large, PlotRange -> {0, 2}, ImagePadding -> 10]     g = OpenRead["****"]     data1 = ReadList[g, {Number, Number}]     b = BarChart[Last[#] & /@ data1, ChartLabels -> (First[#] & /@ data1),     TicksStyle -> {Directive[0.1      , Opacity[0], FontOpacity -> 1],      Directive[12, Opacity[1], FontOpacity -> 1]},     BarSpacing -> Large, PlotRange -> {0, 2}, ImagePadding -> 10]     h = OpenRead["****"]     data1 = ReadList[h, {Number, Number}]     c = BarChart[Last[#] & /@ data1, ChartLabels -> (First[#] & /@ data1),     TicksStyle -> {Directive[0.1      , Opacity[0], FontOpacity -> 1],      Directive[12, Opacity[1], FontOpacity -> 1]},     BarSpacing -> Large, PlotRange -> {0, 2}, ImagePadding -> 10]          Fig = GraphicsRow[{a, b, c}, ImageSize -> 1000]     Export["*****", Fig]      Here is Fig: ![My fig](http://i.stack.imgur.com/ZARcp.png) Here is what comes out of Export: ![enter image description here](http://i.stack.imgur.com/YxqrN.png) You might not be able to see it so clearly, but the 5 in the x-axis is out of alignment with the other numbers, and under magnification looks odd (Zoom in!!!). This is true of the image after Mathematica exports it as a .pdf. 1) Why? 2) How can I avoid this?


title: How to make a resizable chess board?

text: For some reason I need to create a chess board. I can create a chess board by following command:               Graphics[{       EdgeForm[Thick], Black, Rectangle[{0, 0}],       EdgeForm[Thick], White, Rectangle[{1, 0}],       EdgeForm[Thick], , Black, Rectangle[{2, 0}],            EdgeForm[Thick], White, Rectangle[{0, 1}],       EdgeForm[Thick], Black, Rectangle[{1, 1}],       EdgeForm[Thick], White, Rectangle[{2, 1}],            EdgeForm[Thick], Black, Rectangle[{0, 2}],       EdgeForm[Thick], White, Rectangle[{1, 2}],       EdgeForm[Thick], , Black, Rectangle[{2, 2}],            }]      Problem is it has to be resizable (`Manipulate` command). And I should put the numbers for columns and rows. I am going to give one parameter such as board size. The code will generate the board. I believe there is a code for that, but I couldn't find on the internet. Thanks for the help. This is an example, chess board. ![Example chess board](http://i.stack.imgur.com/YxP53.gif)


title: Fit two intersecting straight lines in Mathematica

text: I am trying to do a _Kurie analysis_ of the double beta decay of _Strontium-90_. ![enter image description here](http://i.stack.imgur.com/wlp0v.png) Here we have two straight sections, and I need to obtain a value for the intersection along with an error for it. I cannot fit the linear sections separately and use gaussian error propagation, since the fit parameters are correlated, which leads to a wrong result. My idea was to fit the entire data with one function which is defined piecewise, since the intersection parameter would then not be correlated to the others. However, after several attempts and a fine looking fit, _Mathematica_ reports an error of `0`.               NonlinearModelFit[data, (a*x + b)*UnitStep[x + k] + (c*x + d)*UnitStep[k - x],        {{a, -6.5}, {b, 3}, {c, -1}, {d, 1.8}, {k, 0.55}}, x, Method -> "NMinimize"]      ![enter image description here](http://i.stack.imgur.com/oHSwV.png) Are there any other ways of doing this? * * * As requested in the comments:               data = {        {2.160471686147928`, 0.14147102932224526`},{2.0826390189609363`,0.19988842616357125`},        {2.018773794495269`, 0.2541246545339056`}, {1.9476326649797793`, 0.3042648279519891`},        {1.8745330031773189`, 0.3792877696740006`}, {1.8048469776435923`, 0.4333264807298175`},        {1.731446650327849`, 0.4855243148263505`}, {1.6651014082972075`, 0.5645773920773384`},        {1.5932847071615477`, 0.5972837751080117`}, {1.52139595538298`, 0.6653922271670848`},        {1.4422671545128036`, 0.7171604890149067`}, {1.3757137824715229`, 0.79262676502781`},        {1.3073786844775914`, 0.8404843652309524`}, {1.2337051064574602`, 0.8954499357694174`},        {1.1906240113139641`, 0.9399196660012136`}, {1.1601352767466366`, 0.9890482524748053`},        {1.0867224338785175`, 1.0227388598388758`}, {1.0206577309807057`, 1.0542107134579233`},        {0.9477230432778146`, 1.1301493061594161`}, {0.8733917792374216`, 1.1877273944557323`},        {0.8065623408414323`, 1.2154971541338453`}, {0.736758267792002`, 1.3121152330650923`},        {0.6676435767247085`, 1.3823323706871722`}, {0.635101745155093`, 1.3868057675840053`},        {0.599382518347645`, 1.4179592728730186`}, {0.5622741608125342`, 1.4536070008301036`},        {0.5321771084417978`, 1.4636936970264636`}, {0.490818693322041`, 1.6204857554395113`},        {0.4613963222976981`, 1.6851063997905946`}, {0.42109009911055906`,1.8551603288963705`},        {0.39567303637157025`, 1.945847339995944`}, {0.36747227092332413`, 2.145514603636669`},        {0.34125816875918824`, 2.333372509561687`}, {0.3124933023702082`, 2.347039270807089`}};


title: TabView: Reset some dynamic variable on tab selection

text: Given a `TabView` panel like this one               TabView[{       DynamicModule[{x = False}, {Checkbox[Dynamic[x]], Dynamic[x]}],       "foo"}]      I would like to reset the value of `x` to its initial value (`False`) every time the first tab gets selected - that is, I basically want to "reset"/"reload" the tab on each selection. Also, the variable(s) in question should remain _local_ variables on a per-tab basis, if possible. This is, I hope to avoid a solution declaring `x` globally. Any help very much appreciated (either on reloading the whole tab or on setting specific dynamic variables).


title: Are webMathematica functions totally different compared with Mathematica?

text: Recently, I configured `WebMathematica` in my system. I tested with inbuilt examples, all are working fine. Basically, `Helloworld` program returns `Date[]` output. I tried with `Dynamic` wrapper around `Date[]`, the corresponding code is below.                <msp:evaluate>       Dynamic[Date[]]      </msp:evaluate>      I restarted server, it's not working. It shows `Dynamic[Date[]]` as output. In the same way I tried `Button`instead of `Date`, the corresponding code is below, it's also not working, it returns _Mathematica_ code.                <msp:evaluate>       Button[Style["Click", Black, Bold,25], (MessageDialog["This is Tested by Grandhi..."]), ImageSize -> {180, 60}, Background -> LightGray]      </msp:evaluate>      I have 3 questions. 1.How can I fix this problem ? 2.where can I get good WebMathematica examples? 3.Do all _Mathematica_ functions work in `WebMathematica`?


title: Set theoretic operations on sets of real numbers

text: I have two pieces of code that produce a bunch of real numbers, say $A$ and $B$ respectively. (It is not relevant to the question, but $A$ consists of eigenvalues of the Hamiltonian of some physical system, so these are all energies, and $B$ are some energies computed based on an ansatz.) In theory, it should be the case that $B \subset A$. Because these sets seem to grow quite fast, and because the code is prone to bugs (like $+1$ instead of $-1$, or need for assumptions that some parameter does not become $0$), I would very much like to have an _automated_ way of checking if the inclusion $B \subset A$ really holds for the produced sets. If $A$ and $B$ were just sets of, say, integers, it would suffice to check that: `Complement[B,A]=={}` evaluates to `True`. However, we are dealing with reals in finite precision arithmetic, so `A` and `B` consist merely of approximately equal numbers. I tried a workaround like first projecting them to lower precision, and then doing the check: `Complement[N[B,4],N[A,4]]=={}` (the number of digits that agree is always much greater than $4$ so far, and if there is a difference because of a bug, it has always been within the first couple of digits). Unfortunately, this does not work reliably (I suspect because $A$ and $B$ might be rounded differently if close to some boundary value). Also, this approach isn't too elegant. Could someone suggest a better way?


title: Organizing Code

text: Are there any recommended ways to organize code? THe simulation project I'm working on has gotten a little unwieldy. I've read up on packages but have never used them before. It seems fairly straightforward? Right now I have all my code for this simulation in 3 cells:               Cell 1: Function definitions     Cell 2: Parameter Initializations     Cell 3: Main time stepping loop      This way of working seemed reasonable when the code was small but it has gotten unwieldy. Modifying function definitions is problematic since the variable names used in function definitions tend to be used in Cells 2 and 3, so they have to be Cleared in order to re-run the cell with the function definitions. I'm thinking I should just move the function definitions into a package? Then if I modify a function I do it in the package and just rerun the Package? If some of the arguments in the functions in the package are also used in the notebook where I'm working this won't cause any problems as the package won't know about the notebook?


title: How to use ContourPlot3D for Piecewise 3D function

text: How would I plot in 3D: $\begin{cases} (4 - z^2) = x^2 + y^2, 2 \le z \le 4 \\\ x^2 + y^2 = 4, -2 \le z \le 2 \end{cases}$. I tried http://reference.wolfram.com/mathematica/ref/Piecewise.html `ContourPlot3D[ Piecewise[{(4 - z)^2 == x ^2 + y^2, 2 \le z \le 4}, {x^2 + y^2 = 4, -2 \le z \le 2}], {x, -3, 3}, {y, -3 , 3}, {z, -2, 4}]` I realise there's tex in my code but I don't know how otherwise to symbolise my attempt.


title: Numeric mixed derivatives

text: **In short** I need _NumericCalculus`ND_ extended to mixed partial derivatives. This can be done by nesting them, but care has to be taken to evaluate underling ND only when the parameters become numeric. There are examples in the answers on "Numerical partial derivative" and "Numeric calculation of Hessian" (make sure to notice the discussion on the efficiency). The challenge is to build such patterns with arbitrary number of parameters. **Long story** I am forced to take the derivative of my 200k leafcount expressions numerically. I am aware of _NumericCalculus`ND_ which works great, but does not allow mixed derivatives. There are some examples on how to do it efficiently in this and this answer. I would like to play around with a greater number of parameters and use a `Scale` option for each of them. So I would like to have a nice top level function. An example of what I would like it to be capable of:               nd[Sin[x Conjugate[y]] Cos[u v] /.{u->u0, v->v0}, {x, x0}, {y, y0}, Scale -> {xScale, yScale}]      To define such a function with variable number of parameters and understanding the syntax in some of the examples is beyond my capabilities. Could someone provide the function? It is a pity that _Mathematica_ does not ship with one. **Update to the long story:** Both of the related answers I linked discuss how the underling ND should be called only, when all parameters are finally numeric. This avoids big number of ND calls with partially numeric expressions. I would like the method to have the same feature and not just nesting the ND calls. **Update 2** As I did not consider it relevant, I did not mention that I have complex variables. In this case finite difference method is ill defined and some simple reimplementation of ND would not do.


title: Solving numerically system with Mathematica

text: I'm trying to solve the following system with Mathematica:               Poblacion = {       {1900, 1.65},       {1910, 1.75},       {1920, 1.86},       {1930, 2.07},       {1940, 2.30},       {1950, 2.53},       {1960, 3.02},       {1970, 3.70},       {1980, 4.45},       {1990, 5.30},       {2000, 7.29}       }          P[t_] := 1 / (-q (K t + C))^(1/q)          NSolve[{P[1900] == 1.65, P[1910] == 1.75, P[1920] == 1.86}, {K, q, C}]      But I can't get it working. Could you please tell me what I'm doing wrong?


title: How to get all permutation of k-partition

text: If I want to get the list of k-partition, and the rule are below:   1. here are `k` partitions   2. all elements of partition are in the range of 1 to 30.   3. the total of element from each partition equals to 30. For example, if `k=5`, the partition includes {1,1,1,1,26},{1,1,1,2,25},{1,1,1,3,24}...... Many thanks!!!


title: How to improve this code for exploring large matrices?

text: What I'm actually trying to do is to elaborate this question. I'd like to use `Pane` with scrollbars enabled to explore large (sparse) matrices like this one: ![enter image description here](http://i.stack.imgur.com/X6rNA.png) Here is what I have so far using some ideas from this answer:               A = ExampleData[{"Matrix", "HB/west0381"}, "Matrix"] // Normal;     {n, m} = Dimensions@A;     mp = MatrixPlot[A, ImageSize -> 9 m, Mesh -> All];     DynamicModule[{trans, ij, mpos},      trans[{x_, y_}] := {Clip[Floor[n - y] + 1, {1, n}],        Clip[Floor@x + 1, {1, m}]};      Pane[       Show[mp, ImagePadding -> {{40, 20}, {20, 20}},        Epilog -> Text[           Framed[            Dynamic[(ij = trans@MousePosition["Graphics", {0, 0}]) ->               A[[Sequence @@ ij]]], Background -> White],           Dynamic[MousePosition["Graphics", {0, 0}]],           {1, -1}           ]~Style~Larger        ],       {500, 500},       Scrollbars -> True]      ]      The result is ![enter image description here](http://i.stack.imgur.com/SLaS3.png) * * * **Now about the problems** **1.** The main trouble is that it does not correctly translate coordinates for horizontal scrolling. If we don't touch the horizontal scrollbar everything is fine: ![enter image description here](http://i.stack.imgur.com/RP8aZ.png) But if I slide horizontally the label shifts and falls outside the visible area. It looks like a Mma bug. **2.** The second funny thing is that if I remove `//Normal` from the first row then `MatrixPlot` produces the following: ![enter image description here](http://i.stack.imgur.com/JIChf.png) which seems to be the second bug. **3.** And finally the issue which is due to my confusion with `Dynamic` things. In the code I use `MousePosition["Graphics", {0, 0}]` twice (can this be the reason for the item 1 from above?). When I tried to save this coordinates in a variable I had no luck. But there must be a way to do this. * * * **SUMMARY** Thanks to Andy for resolving problems number 2 and 3, and to David for nice solution using `MouseAnnotation`. I accept kguler's answer since it resolves the main problem with runaway tooltip by effectively using `CoordinatesToolOptions` option. Here is complete working example with kguler's solution. Try it (to enable the tooltip right-click on the plot and select "Get Coordinates"):               mtrxPlot2[mat_, opts : OptionsPattern[]] :=       With[{dims = Dimensions[mat],        indx = {Clip[Floor[#1[[1]] - #2[[2]]] + 1, {1, #1[[1]]}],            Clip[Floor[#2[[1]]] + 1, {1, #1[[2]]}]} &},        With[{copiedvalues =           "CopiedValueFunction" ->            Function[pt, {indx[dims, pt], Extract[mat, indx[dims, pt]]}],          coordtooltips =           "DisplayFunction" ->            Function[pt,             Row[{"mat[[", Row[indx[dims, pt], ","], "]]  =  ",               Extract[mat, indx[dims, pt]]},             Background -> White,             ImageSize -> {Automatic, 30},             ImageMargins -> {{5, 5}, {10, 10}},             Alignment -> Center]]},        MatrixPlot[mat, opts,          CoordinatesToolOptions -> {coordtooltips, copiedvalues}]        ]       ]          A = ExampleData[{"Matrix", "HB/west0381"}, "Matrix"];     Pane[mtrxPlot2[A, ImageSize -> 3000, Mesh -> All,        MaxPlotPoints -> 500], {500, 500}, Scrollbars -> True]


title: How to force mathematica v.9 and 10 notebooks to open in their respective front end

text: I have version 9 and 10 installed on Windows 7. if I double click to open version 9 notebook, then it opens in version 10, how I can force a notebook to open in its respective front end. I have installed both versions: with different init: link


title: Delete `x,y,z` occurrence (or any permutation of it) from parent data set (dynamically)?

text: Simple question: I would like to dynamically specify a list of 3 elements, `{x,y,z}`. Then I'd like to find that list, _or_ any of its permutations, in a parent data set. The parent data set is composed of lists which are at least 3 elements long (like mine), but could also be 4 or 5 elements long. I will then be dynamically deleting the entire part which has an occurrence of `x,y,z` or `z,x,y` etc. from the parent data set (list of lists). The first way I tried doesn't work for obvious reasons (I've removed `Dynamic` functionality because it doesn't work anyway):               data={{0,0,0},{1,1,1},{1,2,3},{3,2,1,9}};     x=3;     y=1;     z=2;     DeleteCases[data,Permutations[{x,y,z}]]      As you can see, I want this to find and delete the 3rd and 4th elements, so that `{{0,0,0},{1,1,1}}` is returned. I'd also like to update `{x,y,z}` dynamically. Are there any tricks to make this work? Or am I doing it entirely wrong? Thanks!


title: How to draw a pane with rounded corners?

text: Pane[      Style["text is here", Bold, FontColor -> Darker[Gray, .6],       Background -> Red       ],      Alignment -> {Center, Center}      ]      ![Mathematica graphics](http://i.stack.imgur.com/T5Gcp.png) How to let the pane have rounded corners?


title: Conditional Data Selection, efficiency

text: Building up on the solution proposed here : Simplifying nested If statements You can find here the data set : allGazes.dat               allGazesX =       Uncompress@        Import[FileNameJoin[{NotebookDirectory[], "allGazes.dat.gz"}],          "String"];      I need to filter large data set and believe I lack an efficient method to do so. The purpose here is to filter given the `EuclideanDistance[]` between gazes. Below is what I am using currently : This is what i am using currently :               GZ[delta_] := ParallelTable[                   Table[                         Reap[z = allGazesX[[subNO, dispNo, 1, ;; 2]];Sow[z];                         Scan[                              If[                                 EuclideanDistance[#, z] > delta,                                 z = #;Sow[z]] &,                                 allGazesX[[subNO, dispNo, All, ;; 2]]]][[2, 1]],                        {dispNo, Range[Length[allGazesX[[subNO]]]]}],                   {subNO, Range[5]}];


title: Is there a way to "hold" prefix / infix / postfix notation?

text: Is it possible to preserve a specific style of notation in $Mathematica$ output?               foo // bar     (* bar[foo] *)          Hold[foo // bar]     (* bar[foo] *)      I'm writing some code that generates sample code ( _e.g._ a usage hint), and in one case I feel that postfix notation is easier on the eyes. I know it's subjective and not that important but now I'm just curious whether this is possible to control. * * * ## Edit `Postfix` preserves the notation as @rasher pointed out. However, my intent was to allow convenient evaluation of sample code by being able to immediately evaluate the output—that is, `Shift``Enter` the `foo//bar`. When `Postfix` is the head of an expression though, the evaluation simply returns the expression—which, makes complete sense, since that's what `Postfix`... does. (This question almost seems circular now.) Is there a way, perhaps, to create a custom `PostfixToEvaluate` head that would _display_ the expression in postfix but, maybe via an UpValue, remove itself and evaluate its contents, upon evaluation? (I don't know if that makes any sense. I'm going to try it now...) * * * Tags I considered but don't believe are relevant: stylesheet hold expression- manipulation. Note that I've left "hold" in the title as that's the intuitive keyword by which I would have searched, were I a future visitor.


title: Fourier-Analysis How to display every period correctly?

text: I want to express a function as a sum of fourier series.   I tried the code below. It works. But only get one period (from 0 to 1).   How to display every period correctly?               f = Piecewise[{{10 x, 0 <= x < 0.1}, {-(10/9) x + (10/9), 0.1 <= x < 1}}];     coeff[0] = 1/4 Integrate[f, {x, 0, 1}];     coeff[n_] = 1/4 Integrate[f*Exp[I Pi n x/2], {x, 0, 1}];     series[m_, x_] := Sum[Exp[-I Pi n x/2] coeff[n], {n, -m, m}];     Plot[Evaluate[Table[series[j, x], {j, 1, 5}]], {x, -2, 2}]      ![enter image description here](http://i.stack.imgur.com/gpde1.jpg)


title: Why is this minimization with Boole functions failing?

text: I am running this command in Mathematica 8.0.4.0:               Minimize[(x1*1 - 1)^2 + (x1*0.823202 + x2*1 - 0.7551)^2 +               lambda*(Boole[x1 != 0] + Boole[x2 != 0]), {x1, x2}]      Now, with `lambda=0` (negating the `Boole` functions), I get:               {7.70372*10^-34, {x1 -> 1., x2 -> -0.068102}}      With `lambda=1`, I get:               {2., {x1 -> 1., x2 -> -0.068102}}      It seems to be ignoring the Boole functions, because clearly `x2 -> 0` is a better solution:               (x1*1 - 1)^2 + (x1*0.823202 + x2*1 - 0.7551)^2 +       lambda*(Boole[x1 != 0] + Boole[x2 != 0]) /. {x1 -> 1, x2 -> 0}          1.00464      I assume Mathematica is minimizing this function numerically; is it simply incapable of doing this with `Boole` functions, given their stepwise nature?


title: Multivariate series expansions to different powers

text: I have a function that (I believe) correctly takes the multivariate Taylor series expansion about the origin for some expression (first argument), in some variables (second argument, list), to different orders (third argument, list). My method for taking the multivariate series expansion follows the answer provided here. I take the series expansion to the highest order requested in the list (unless the highest order is infinity, in which case the next-highest is used), then I truncate the series by adding a "big-O" for each variable at its requested order plus one. If the requested order of a variable is infinity, no expansion is performed on that variable.               mySeriesMWE[exp_, x_List, o_List] := Module[       {pos, ow, xw, xDummy},       pos = Position[o, Infinity];       If[(Length[o] < 1) || (Length[pos] == Length[o]),       Return[exp],       ow = o // Delete[#, pos] &;       xw = x // Delete[#, pos] &;       (exp /.              Thread[xw -> xDummy*xw] //             Series[#, {xDummy, 0, Max[ow]}] & //            Normal) /.          {xDummy -> 1} //         # +            Sum[O[xw[[i]]]^(ow[[i]] + 1), {i, 1, Length[xw]}] & //        Normal       ]     ];      Usually, the results are as-expected, but there is a test-case that provides a result that is unintuitive, but I think, technically correct: when the expression is $x y z$ and we compare the expansion at the origin for the powers $\\{1,1,3\\}$ and $\\{1,1,\infty\\}$.               mySeriesMWE[x y z, {x, y, z}, {1, 1, 3}]     mySeriesMWE[x y z, {x, y, z}, {1, 1, Infinity}]     --output--     x y z     0      It was surprising to me that taking the third power in $z$ gave a better approximation (in fact, the entire expression) than not taking the expansion in $z$ at all! I checked in the general case, however, and I think this result is correct:               mySeriesMWE[f[x, y, z], {x, y, z}, {1, 1, 3}] // Expand     mySeriesMWE[f[x, y, z], {x, y, z}, {1, 1, Infinity}]     --output--     f[0,0,0]+z (f^(0,0,1))[0,0,0]+1/2 z^2 (f^(0,0,2))[0,0,0]+1/6 z^3 (f^(0,0,3))[0,0,0]+y (f^(0,1,0))[0,0,0]+y z (f^(0,1,1))[0,0,0]+1/2 y z^2 (f^(0,1,2))[0,0,0]+x (f^(1,0,0))[0,0,0]+x z (f^(1,0,1))[0,0,0]+1/2 x z^2 (f^(1,0,2))[0,0,0]+x y (f^(1,1,0))[0,0,0]+x y z (f^(1,1,1))[0,0,0]     f[0,0,z]+y (f^(0,1,0))[0,0,z]+x (f^(1,0,0))[0,0,z]      The last term in the first output is $x y z$ when the expression is $x y z$, and I believe both expansions match the definition of a multivariate Taylor series about the origin, throwing away the proper higher-order terms. My first question is: is the function valid for orders less-than infinity? (I believe the answer is "yes," but I have never seen a multivariate Taylor series expansion truncated in certain orders.) My second question is: is the function's behavior correct when the requested order of a variable is infinity? My third question is: is there a better way to write the function such that the variable we do not wish to expand in is somehow better-preserved? ## Edit Here's a better way, based on a suggestion by John Sidles. The idea is to "penalize" higher-order terms by weighting the replacement of `xDummy` with an exponent that depends (unintuitively: inversely) on the requested orders of expansion in that variable. Here is the modified function.               mySeriesMWE[exp_, x_List, o_List] := Module[        {pos, ow, xw, n, xDummy, xDummyPower, xDummyList, testList},        pos = Position[o, Infinity];        If[(Length[o] < 1) || (Length[pos] == Length[o]),         Return[exp],         ow = o // Delete[#, pos] &;         xw = x // Delete[#, pos] &;         n = Length[xw];         xDummyList = Array[xDummy^(1 + Max[ow] - ow[[#]]) &, n];         testList = Array[If[#1 == #2, ow[[#1]], 0] &, {n, n}];         xDummyPower =           Max[           Table[            Sum[             testList[[j, k]]*(1 + Max[ow] - ow[[k]]),             {k, 1, n}             ],            {j, 1, n}            ]           ];         (exp /.                Table[xw[[i]] -> xDummyList[[i]]*xw[[i]], {i, 1, n}] //                      Series[#, {xDummy, 0, xDummyPower}] & //              Normal) /.            {xDummy -> 1} //           # + Sum[O[xw[[i]]]^(ow[[i]] + 1), {i, 1, n}] & //          Normal         ]        ];      There is some ambiguity in choosing the order of expansion in `xDummy`. I chose a conservative value (including extra terms) and truncated with `O` in the usual manner, in case an obvious term was missed in the expansion (which does happen).


title: Plot of a periodic triangular wave

text: I'm trying to graph the zig-zag function at the top of this page: http://www.math.ubc.ca/~feldman/m321/nondiffble.pdf I have a little bit of experience with Mathematica but not a ton. Any suggestions?


title: How to find the integer solution number of a linear system with inequalities?

text: I have the following system with mixed equality and inequalities defined as:               n = 100;     eqn = (n1 + n3 + n5 == n2 + n4 + n6) && (n1 >=          n2) && (n1 - n2 + n3 - n4 >= 0) && (n1 <= n) && (n1 - n2 + n3 <=          n) && (n1 - n2 + n3 - n4 + n5 <= n) && (2 n <=          n1 + n2 + n3 + n4 + n5 + n6 <= 6 n) && (n1 > 0) && (n2 > 0) && (n3 > 0) && (n4 > 0) && (n5 > 0) && (n6 > 0);      How can I find all the integer solutions and especially the number of all integer solutions? It seems `Reduce` or `Solve` does not work:               sol = Reduce[eqn, {n1, n2, n3, n4, n5, n6}, Integers]      produces:                 (n1 | n2 | n3 | n4 | n5 | n6) \[Element]        Integers && ((1 <= n1 <= 99 &&           0 < n2 <=            n1 && ((0 < n3 < 100 - n1 && 0 < n4 <= n1 - n2 + n3 &&               100 - n1 - n3 <= n5 <= 100 - n1 + n2 - n3 + n4 &&               n6 == n1 - n2 + n3 - n4 + n5) || (100 - n1 <= n3 <=                100 - n1 + n2 && 0 < n4 <= n1 - n2 + n3 &&               0 < n5 <= 100 - n1 + n2 - n3 + n4 &&               n6 == n1 - n2 + n3 - n4 + n5))) || (n1 == 100 &&           1 <= n2 <= 100 && 0 < n3 <= n2 && 0 < n4 <= 100 - n2 + n3 &&           0 < n5 <= n2 - n3 + n4 && n6 == 100 - n2 + n3 - n4 + n5))


title: Apply a function to a matrix of vectors

text: I have a matrix containing on each position a pair of numbers $(a,b)$. I would like to compute the norm of each vector $(a,b)$ and keep the result in form of a matrix. So basically, I need to apply the function `Norm` elementwise to a matrix of vectors. How could I do that?


title: Define function that goes from one point to another parametrically

text: I have two points p1 and p2, and I want to get the parametric equation of a linear function that passes through those, but ranging from one point to another. For example, if I have 2 points {0,0} and {1,1/2}, the equation would be {t,t/2}. > The goal of having a **parametric equation** is to have the function defined > even when the slope is $\infty$. I tried this (here the angle[] function is Atan2, is basically `ArcTan` but ranging from 0-2π):               Piecewise[      {       {{t, Last@p1 + Tan@angle[p1, p2] (t - First@p1)},         Min[First@p1, First@p2] <= t && t <= Max[First@p1, First@p2]},       {{First@p1, t}, First@p1 == First@p2}       },      Indeterminate      ]      But when a point is on top of the other the function is a vertical line, ranging from $-\infty$ to $\infty$; I would only want the function to be defined from Last@p1 to Last@p2. In other words, I want a Graphics' `Line`, but using parametric equations. Something like this: ![enter image description here](http://i.stack.imgur.com/buJF5.png)


title: Is there a relatively quick way to solve my integer-valued equation?

text: This is a very simple problem. It can be solved by nested `For`loops that exhaustively test every possible case, throwing out all non-solutions. > Find all the distinct positive integer solutions $0<a_i \leqslant 100$, such > that: > > $$\sum\limits_{i=1}^{10}\dfrac{1}{a_i}=1$$ There are 69014 solutions in total. But it will take a long time to find them all by nested `For`loops. Is there an efficient method for this problem, i.e, one that will find all the solutions in less than 20 minutes?


title: Parallel and perpendicular symbol from mathematica to latex

text: I want to get the following expression from mathematica to latex: \begin{bmatrix} E_{\parallel} \\\ E_{\perp} \end{bmatrix} I have tried to use inbuilt 'symbol' character from the special characters window but get an error: ![error](http://i.stack.imgur.com/aYfwh.png) So I thought maybe I can just type in \parallel and \perp so when I convert it to tex it will be there and work, but I get different errors: ![more erros](http://i.stack.imgur.com/Tuzxh.png) Any way to achive what I want? Thanks


title: Manipulating a sublist based on position

text: I have a huge list with huge sublists of the form               list={{a,b,c,d},{e,f,g,h},{i,j,k,l}}      I am looking for a way to manipulate these sublists based on the positions of the elements. Something like               list/.{j_,k_,l_,m_}->{j-1,k,l,m}      but without having to write the whole pattern. Is there any way to specify such manipulation based on the position of the element? Something like               list/.#[[1]] & -> #[[1]] - 1 &      that would work?


title: WordData [ ] returns ReplaceAll::reps error message

text: # Situation:               In:= w = WordData[];     During eval of In:= ReplaceAll::reps: {Expression/. Null} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.[>>][1]     During eval of In:= LinkOpen::linke: Specified file is not a MathLink executable..[>>][2]            In:=  WordData["Day", "Definitions"]     Out:=  WordData["Day", "Definitions"]            (*last seems unevaluated...*)            In:=  Here     Out:=  Missing[NotAvailable]    ## Intention: I am simply calling this function to use it but its not working.   * I am connected to the internet and I am able to call WolframAlpha["query"] sucessfully...   * Any idea that do not include acrobatics with the Mathematica File System is more than welcome...   * I already check my firewall settings ... ## Here is another one:               In:=  CountryData[]     Out:=  DataPaclets`CountryDataDump`$GroupHash["Countries"]        * Any ideas...?       ## System Info:               ~$uname -a     Linux ***** 3.16.1-1-ARCH #1 SMP PREEMPT Thu Aug 14 07:40:19 CEST 2014 x86_64 GNU/Linux         Network information:               In[2]:= SystemInformation["Network"] //Column                                             Out[2]:= IPAddresses -> {fe80::****:274c:a7c7:***, 192.168.1.145}             AllowInternetUse -> True             LoadOnDemand -> True             LoadOnDemandServers -> {http://pacletserver.wolfram.com}             LatestTransaction -> Missing[NotActive]             LatestTransactionServer -> Missing[NotActive]             LastLocalIndexUpdate -> {2014, 8, 28, 19, 11, 30.766294}             LastLocalIndexUpdateServer -> {}             Paclets -> PacletManager Version 2.2.0             TotalDownloads -> Missing[NotActive]             DownloadsDirectory -> Missing[NotActive] Mathematica Kernel Information:               In[3]:= SystemInformation["Kernel"] //Column                                              Out[3]:= Version -> 10.0 for Linux x86 (64-bit) (June 29, 2014)             ReleaseID -> 10.0.0.0 (5098646, 5098517)             LicenseID -> *****-****             PatchLevel -> 0             ActivationKey -> ****-9190-****             ActivationGroupID -> *****-****             MachineID -> 6539-*****-01360             UserName -> *****             MachineName -> ****             MachineDomains -> {sd.cox.net}             LicenseServer -> gabriel             MaxLicenseProcesses -> Infinity             LicenseExpirationDate -> {Infinity, 0, 0, 0, 0, 0}             MachineType -> PC             OperatingSystem -> Unix             ProcessorType -> x86-64             Language -> English             CharacterEncoding -> UTF-8             SystemCharacterEncoding -> UTF-8             TimeZone -> -7.             CreationDate -> DateObject[{2014, 6, 29}, TimeObject[{19, 7, 59}]]             InstallationDirectory -> /usr/local/Wolfram/Mathematica/10.0             WSTPVersion -> 4.25 (2014062701)             ProcessorCount -> 2             LicenseSubprocesses -> 1             MaxLicenseSubprocesses -> Infinity      I also tried `Trace` and `TracePrint` on the `WordData[]` function call. _Nothing clear so far ..._    This is a **__link_ to the output_** of:               System`Dump`AutoLoad[Hold[CountryData], Hold[CountryData], "DataPaclets`CountryData`"] // TracePrint    Wolfram Documentation: ReplaceAll::reps error docs.      LinkOpen::linke error docs.


title: Kalman filter by hand

text: I am now learning the Kalman filter and wants to implement it by hand to understand it better. To be specific I want to first simulate a sequence of data by $$ \dot x=Ax+Bw\\\ y=Cx+Dv,\\\ E[x(0)]=0,E[x(0)x'(0)]=P_0, $$ where $w,v$ are white noise processes with unit variance. Then I need to construct the Kalman filter by $$ \dot{\hat x}=A\hat x+QC'(y-C\hat x), \hat x(0)=0 $$ where $Q$ solves the ricatti differential equation $$ \dot Q=AQ+QA'-QC'CQ+C'C,Q(0)=P_0. $$ I have two questions:   1. How do I generate the sequence of data governed by a differential equation?   2. How do I solve the ricatti differential equation? I know this post shows no effort, but I am new to mathematica and have no idea where to start (especially that I cannot generate the data needed, which stops me from any progress). Any hint is appreciated.


title: Left-aligned PlotLabel?

text: Is it possible to have the text generated by `PlotLabel` (or any other function) aligned to the left side of the plot instead of in the center?


title: StringMatchQ and Alternatives throws message in init.m

text: The report of this issue, which itself relates to code of my answer here, exposed a behavior I cannot explain. If I use `StringMatchQ` in combination with `Alternative` inside the `init.m` a message is thrown on start of the kernel. You can test this by putting this line in your `init.m`               StringMatchQ["name", "noMatch" | "name"];      and when you start the kernel you see two messages saying > Throw::nocatch: Uncaught Throw[False] returned to top level. Surrounding the statement by `Catch` does not help. The solution is to substitute this regex-alternative into a logical `Or`               StringMatchQ["name", "noMatch"] || StringMatchQ["name", "name"]      but that doesn't explain the issue. What am I missing here?


title: Solving recurrence relation using Mathematica defined in a piecewise way

text: I have a recurrence relation defined as following:               RSolve[      {       p[0] == p0,       p[1] == λ p[0]/μ,       p[i + 1] == λ p[i]/(2 μ)       },      p[i], i     ]      Note that the relation is differently for `i=1`, than for `i >= 1`. This yields the following error: > DSolve::bvnul: For some branches of the general solution, the given boundary > conditions lead to an empty solution. >> When I use `Piecewise`, Mathematica just echos the input:               RSolve[      {       p[i + 1] ==         Piecewise[{          {p0, i == -1},          {λ p[i]/μ, i == 0},           {λ p[i]/(2 μ), i >= 1}}]       },      p[i], i     ]      Also using `If` or `Condition` does not to work out. Appreciate your help! (Btw, this simple example can easily be solved by hand, but I would like to solve more complicated recursions involving piecewise definitions.)


title: Mathematica9 linux version crash, how to fix it?

text: Ubuntu 12.04 x86_64 kernel 3.2.0-35-generic _Mathematica_ 9 linux version (x86_64) crashes with errors: > X Error of failed request: BadGC (invalid GC parameter)   >  Major opcode of failed request: 59 (X_SetClipRectangles)   >  Resource id in failed request: 0x0   >  Serial number of failed request: 2266   >  Current serial number in output stream: 2268 > > X Error of failed request: BadGC (invalid GC parameter)   >  Major opcode of failed request: 59 (X_SetClipRectangles)   >  Resource id in failed request: 0x0   >  Serial number of failed request: 2267   >  Current serial number in output stream: 2268 > > ... The above errors occur when I run command `mathematica` as a general user. It crashes before GUI is started. However, if I run it as root `sudo mathematica`, all work well. Can someone fix this problem?


title: Vertex labels versus vertex names in VertexRenderingFunction

text: The VertexRenderingFunction seems to only use names, not labels. For example:               GraphPlot[Import["D:/dev/ProjectEuler/keylog.gv"],VertexLabeling->True,PlotStyle->{Black},VertexRenderingFunction->({EdgeForm[Black],White,Disk[#1,0.08],Black,Text[#2,#1]}&)]      The imported gv file here has both names and labels defined for each node. The names are always unique, but the labels are not necessarily unique. Unfortunately, the above GraphPlot only shows the NAMES of the vertices, not the labels. How can I get the labels and not the names? ![enter image description here](http://i.stack.imgur.com/kdM22.png) The vertex annotations above are names, not labels of each vertex. The DOT file is as follows:               digraph Passcode {         0 [label="3"];         1 [label="1"];         2 [label="9"];         3 [label="6"];         4 [label="8"];         5 [label="0"];         6 [label="2"];         7 [label="7"];         0 -> 1;         0 -> 2;         0 -> 3;         0 -> 4;         1 -> 4;         1 -> 6;         1 -> 5;         1 -> 3;         1 -> 2;         2 -> 5;         3 -> 4;         3 -> 2;         3 -> 6;         3 -> 5;         4 -> 5;         4 -> 2;         6 -> 2;         6 -> 5;         6 -> 4;         7 -> 3;         7 -> 1;         7 -> 6;         7 -> 0;         7 -> 2;     }


title: What does the slash-colon symbol do?

text: I came across a bit of code that uses the syntax `/:` and I don't know what it does. I can't find its documentation, or maybe I'm just not looking properly. The code snippet is something like:               F/:F[A___,b_?NumberQ B_, C___] := b*F[A,B,C]      (i.e. part of the definition of multi-linearity). How does this behave differently than the following?:               G[A___,b_?NumberQ B_, C___] := b*G[A,B,C]      Thanks!


title: Functions in a different context are replaced with infix forms of their namesake in System`

text: So, in an attempt to help out Fabian with his question, I did what I often do, and created a new symbol in the `Pillsy`` package that I could play with. Since it was in a package I control completely, I thought, "Hey, I can just call it `Times`!". I was really surprised when this happened:               In[3]:= Pillsy`Times[a, b, c]     Out[3]= a * b * c      It looks like Mathematica uses just the symbol name in determining whether to replace something with infix syntax, without paying attention to the context. However, I'm fairly sure I've never seen it happen before and I don't recall coming across it in the documentation. Evidently specifying `InputForm` shows you the whole thing:               In[4]:= Pillsy`Times[a, b, c] // InputForm     Out[4]= Pillsy`Times[a, b, c]      This is in contrast to the `InputForm` for `System`Times`. Is this an intentional feature (it's hard to imagine otherwise), and if so, how does it interact with things like `MakeBoxes`, `MakeExpression` and `Format`? Also, how do you avoid being burned by it? I'm a little alarmed that my assumption that `a * b * c` is the same thing as `System`Times[a, b, c]` is unfounded, even in the absence of changes to `$Post` and the like.


title: What is so special about Prime?

text: When we try to evaluate `Prime` on big numbers (e.g. `10^13`) we encounter the following issue :               Prime[10^13]      > >     Prime::largp: Argument 10000000000000 in Prime[10000000000000] is too > large >     for this implementation. >> >     Prime[10000000000000] >   Following this message we can read in M - documentation that the largest supported argument in `Prime` is typically about 2^42. With a kind of divide and conquer approach we can figure out that the maximal argument of `Prime` is :               OmegaPrime = 7783516045221;      **1\. What determines this number ? A hardware/software and/or conceptual/mathematical issue or maybe is it an arbitrary system cut-off ?** The problem seems to be a bit more obscure since one encounter something like this :               Prime@{# + 1, #, # + 1} & @ OmegaPrime      > >     Prime::largp: Argument 7783516045222 in Prime[7783516045222] is too > large for >     this implementation. >> >     {Prime[7783516045222], 249999997909357, 249999997909367} >   (It takes more than two minutes to evaluate) An analog of `OmegaPrime` is `OmegaPrimePi` for `PrimePi` :               OmegaPrimePi = 25 10^13 -1;      I can find even bigger primes with `Prime` if I evaluate for example :               Select[Range[249999997909357, 25 10^13], PrimeQ] // Length      > >     63142Q >                 Prime@( OmegaPrime + 63142 )      > >     250000000000043 >   However I cannot evaluate `PrimePi` for numbers greater than `OmegaPrimePi`. It appears that `Prime` has a dynamically extensible domain while `PrimePi` has not. **2\. How do I detect this property in advance from the system ?** I mean not to play around with e.g. `Select[Range[a,b], PrimeQ]`, but for example to read it from `Attributes` or anything else.


title: Limits of PrimeNu

text: Is there any way to find distinct prime factors for very large numbers using `Prime` and/or `PrimePi` that exceeds the capabilities/limits of `PrimeNu`?


title: Internals of Prime function

text: Does anyone knows how exactly `Prime` works ? For example how `Prime[1000000000]` is calculated ? The only information I found was some inequalities in Wolfram's Function site. Thank you.


title: differential equations with implicit functions

text: I have an ordinary differential equation that contains coefficient functions that depend implicitly on the independent variable via an algebraic equation. I am trying to go ahead and use NSolve to solve for that coefficient function, but it doesn't work, even approximately. The problem seems to be in the evaluation of NSolve, but I can't fix it. Anybody knows help?               PP=a^5+a^2 +3w+4          (* 4+a^2+a^5+3 w *)          sol=NDSolve[{f'[w]==(a/.NSolve[PP,a][[1]]),f[0]==0},f,{w,0,3}][[1]]          (*Out[2]= {f->InterpolatingFunction[{{0.,3.}},<>]}*)          f'[0]/. sol          (*Out[3]= -1.13496*)          NSolve[PP/. w->0,a][[1]]          (* Out[4]= {a->-1.43359} *)


title: How can I obtain a zero-filled Fourier transform, as produced by MATLAB's fft?

text: The MATLAB FFT function, `fft(X,n)`, can be used to return the _n_ -point DFT. This effectively extends the original signal, `X`, to `n` points if `n` is larger than the dimension of `X`. But, with the `Fourier` function in _Mathematica_ , the transform always has the same dimensions as `X`. So, how can I obtain the same behaviour in _Mathematica_ as implemented in MATLAB?


title: Reversibly abstracting a list of strings as a graph object where vertices represent strings and edge connect pairs of strings based on various tests

text: Imagine I provide you a list of arbitrary strings, say: `Map[StringJoin, Tuples[{"0", "1", "2"}, 4]]`. I'd like to abstract these strings as a graph object in Mathematica v9, where each string $s_i$ becomes a vertex $v_i$, and two vertices $(v_a,v_b)$ share an edge if one or more test cases return `TRUE` for the two strings. For example, if `EditDistance[sa,sb] > 3` is `TRUE` and if `StringReverse[sa] == sb` is `TRUE`, then I'd like the respective vertices $v_a$ and $v_b$ to share an edge. Once I've performed some graph operation to generate a subgraph of the original graph, I'd like to pull back down the list of strings corresponding to the vertices in this subgraph. Being new to Mathematica v9's treatment of graphs, what would be the best way to proceed here? Is it at all reasonable to do this for large sets of vertices, $10^5$ or so?


title: How to make Layer Directed Graphs (LDG) in mathematica?

text: I am wondering if I can make a graph like that somehow: ![LDG Graph for a Chemical Process Industry](http://i.stack.imgur.com/w6pwO.png) I am new to mathematica, I tried to play with Creating a graph with variable size of vertices and variable thickness of edges . I figured if I could get the data in that form I could make some changes and try to adapt it to mine. But that is not working. Can someone help me please?? This is what the data sample looks like in tabulated form: ![enter image description here](http://i.stack.imgur.com/pYJXr.png) I used this:               trans = Uncompress@     "1:eJxTTMoPShNkYGAoZgESPpnFJWlMIB4PkHDJLEpNLklNcU1JTy1mBEkXg+\     TcDAkrMcKjJASsJASXKWBJI4hKPErcIEp8BolzIdRAuxdqEUE/Uc0mfF5CdowhABdjfqo=\      ";     l = VertexList[Graph[trans]];     (*Weigths for vertices*)     r = RandomReal[{0.5, 1}, Length[l]];     vs = Transpose@{l, r} /. List[a_, b_] -> Rule[a, b];     (*Adjust font size*)     vls = Transpose@{l, r} /.      List[a_, b_] -> Rule[a, Directive[Black, Bold, 20*b]];     (*Weigths for line thicknes*)     rr = RandomReal[{0.1, 1}, Length[DeleteDuplicates@trans]]/100;     es = (First@# > Directive[Thickness[Last@#], Opacity[.5]]) & /@      Transpose@{DeleteDuplicates@trans, rr};     g = Graph[DeleteDuplicates@trans,      VertexLabels -> Placed["Name", Center],      VertexShapeFunction -> "Capsule", VertexSize -> vs,      VertexLabelStyle -> vls, EdgeStyle -> es,      EdgeShapeFunction ->      GraphElementData["ShortUnfilledArrow", "ArrowSize" -> 0.03]]      and got this, which is not what I need   ![Graph](http://i.stack.imgur.com/u7PVH.gif)


title: How do I find the equation of line based on two points in WolframAlpha?

text: What would be the proper syntax to enter in WolframAlpha to find the equation of line, if I know two points on it. I know how to do it by hand, but I want to get into the proper syntax of WA.


title: Unexpected behavior of GeometricTransformation

text: I have the following mapping on the complex plane: $$ z \mapsto \tau \mu z-1, $$ where $\mu$ is complex, $\tau$ is real number. I want to draw the image of left unit semidisk and play with $\tau$.               μ = 0.16255558520216132` + 0.1849493244071408` I;          pic[τ_] := Block[{d, ds},        d = Disk[{0, 0}, 1, {π/2, 3 π/2}];        ds =         Fold[GeometricTransformation, d,            {RotationTransform[Arg@#, {0, 0}],             ScalingTransform[τ Abs@# {1, 1}],             TranslationTransform[{-1, 0}]             }] & @ μ;        Graphics@{Gray, d, Red, Opacity[.5], ds}        ];          Manipulate[      Dynamic@Show[pic[τ], Frame -> True, Axes -> True,         AxesOrigin -> {0, 0}, PlotRange -> zz {{-100, 100}, {-100, 100}},        ImageSize -> 400        ],      {τ, 0.01, 1000, 0.01},      {zz, 0.01, 10, 0.01}      ]      Here `zz` is introduced to control zooming. The problem is that I get different (wrong) images for different zooms. It is clearly seen for big $\tau$'s. ![enter image description here](http://i.stack.imgur.com/A33DX.png)![enter image description here](http://i.stack.imgur.com/r4Lll.png)![enter image description here](http://i.stack.imgur.com/2rooj.png) It looks very like a bug, but I can not rule out that I'm making some silly mistake (Mathematica 8.0.4). So, what is the problem here and what is the best way of doing the job (I have several mappings for different $\mu$ actually)?


title: Generating a power series expansion of the function with parameter

text: I'm trying to generate a power series expansion of the following function:                S[x_, l_] :=         (C[1] + Integrate[E^(2 Sum[t^i/i, {i, 1, l - 1}]) (1 - t)^2               Sum[(l - i*2) t^i, {i, 1, l - 1}]/((t - 1) t^l), {t, 1, x},              GenerateConditions -> False])*x^(l - 1)*E^(-2 Sum[x^i/i, {i, 1, l - 1}])/(1 - x)^2;      For `l=2` and `l=3` it works perfectly, but not in case of `l=4`:               Table[CoefficientList[Series[S[x, i], {x, 0, 4}], x], {i, 2, 4}]      Is it possible to solve this problem?


title: Extending a ternary plot to a tetrahedron (using ListPlot)

text: I have been making ternary plots of data that is a list of sets of 3 numbers, where the numbers in each set sum to one (call this "DATA"). To do this, I first transform DATA onto the 2D surface with the following:               transf[{a_, b_, c_}] := {b + c/2, (Sqrt[3] c)/2}          Map[transf,DATA].      This gives a list of sets of 2 numbers that map onto a simplex (call this DATA2). This is how I've plotted DATA2:               Show[{       RegionPlot[Sqrt[3] a1 - a2 < 0, {a1, 0, .5}, {a2, 0, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       RegionPlot[Sqrt[3] a1 + a2 > Sqrt[3], {a1, .5, 1}, {a2, 0, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       RegionPlot[a2 < 0, {a1, 0, 1}, {a2, -.2, 1},         DisplayFunction -> Identity, PlotStyle -> White,         BoundaryStyle -> None],       ListPlot[{{0, 0}, {1, 0}, {.5, Sqrt[3]/2}, {0, 0}}, Joined -> True,         PlotStyle -> {Black, Thickness[.015]}],       ListPlot[{DATA2}, Joined -> True,          PlotMarkers -> Automatic]},      AspectRatio -> Automatic, Frame -> False,       PlotRange -> {{0, 1}, {0, 1}}]       Example: ![example of two data sets plotted on the simplex](http://i.stack.imgur.com/zr8Pw.jpg) Question: Now, I have an extended data set that is made up of sets of 4 numbers that sum to one. I'd like to plot the data in an analogous way, but now on the corresponding tetrahedron. However, I'm not sure how to transform the data or how to draw the appropriate tetrahedron. Can anyone help with this, please?


title: How to get shadow of a 3d object

text: Suppose that we have a box or a sphere or an other 3D object and a ponctual light source. How we can generate the cast shadow using mathematic? Is there any tools to render a shadow given the light source position?


title: Filling between two spheres in SphericalPlot3D

text: Manipulate[      SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi},        Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0,        1}]      I cant' seem to be able to make a filling between two spheres. I've already tried the obvious `Filling -> {1 -> {2}}` but _Mathematica_ doesn't seem to like that option. Is there any easy way around this or ...


title: Add coordinate axes to a 3D plot of concentric spheres

text: I want to add coordinate axis to a figure of nested spheres. I have the command.               Graphics3D[Table[{Opacity[.6], Specularity[White, 20], Sphere[{0, 0, 0}, r]},      {r, 1/2, 3, 1/2}], Boxed -> False]      Which reproduces the set of nested spheres ![enter image description here](http://i.stack.imgur.com/5tN0r.jpg) Now, I would need to add axes X, Y and Z It would also be good to be able to label the spheres 1, 2, 3... Thanks Edit: and to do something similar to this picture? ![enter image description here](http://i.stack.imgur.com/4Nywf.png)


title: Iterative way to find roots of confluent hypergeometric function

text: I am trying to find roots of confluent hypergeometric function and I wonder if I can choose the initial guess by the choice of $\beta$.               eq[n_, \[Beta]_, \[Lambda]_] :=                                     Hypergeometric1F1[1/4 (2 - \[Lambda]/\[Beta]), n + 1, \[Beta]]     ED[n_, \[Beta]_, k_Integer: 1] := \[Lambda] /. FindRoot[eq[n, \[Beta], \[Lambda]] == 0,                                             {\[Lambda], (4 k - 2) \[Beta]}]      My goal is to plot the function (x-axis:$\beta$ and y-axis:$\lambda$). To do that, I need good $\lambda$-values for each $\beta$. The problem is that for each $\beta$ we can have lots of roots, so I want to choose $\beta$ depends on the previous $\lambda$-value for initial guess to find the next root. For example, Start from $\beta=0$. For $\beta=0$, I want to find a root, $\lambda$, around $BesselJZero[n,k]^2$. Next, For $\beta=1$, I want to get a root around $\lambda$-value at $\beta=0$. Then, for $\beta=2$, I want to get a root around $\lambda$-value at $\beta=1$ and so on. For the iterative way I think I should use "for loop" or "if", but I am not sure how to use it. Could you help me out? Thank you.


title: How do I create and use Mathematica packages?

text: I have created a package following the tutorial in _Mathematica_ 8 virtual book. However this tutorial is quite, let's call it, "short". I have a `TestPackage.m` file:               BeginPackage["TestPackage`"];     TestPackage::usage = "Test package"          Begin["`Private`"]     TestPackage[1] := {1}       (*private functions and stuff*)     Mesg := Print["Private function of TestPackage"]     End[]          TestPackage` f[x_] := Module[{a = 3, b = 3}, Mesg; a x^b]          EndPackage[]      and a file `UseTestPackage.nb` that uses the package:               ClearAll["Global`*"]     dir = "C:/...and so on"     Get["TestPackage`", Path -> dir]          f[2] (*this should give an output defined in TestPackage.m, but it doesn't*)          $ContextPath          (* {"PacletManager`", "WebServices`", "System`", "Global`"}*)     (*seems it didn't read the m file*)      but nothing happens. No symbols of functions are exported, despite the fact that `Get[]` doesn't throw an error. How do I make it work?


title: How to import date (YYYY-MM-DD) data from a file?

text: I have a file with data in form `{date, value}`:   `2010-05-19 17`   `2010-05-20 20`   `2010-05-21 19`   `...`   How would I import such data in form `{DateList, value}`?


title: Outputting a film (in .avi, .mp4, etc. formats) where frames correspond to Graphics3D outputs

text: I'd like to make a exportable film (in some format like .avi or .mp4, something playable on most computers) where each frame is a Graphics3D output. For example, we might generate frames in the following way:               polytopeSize = 3;          numFrames = 10;       frameSet = Table[Graphics3D[Table[Translate[Scale[PolyhedronData["Dodecahedron", "Faces"], polytopeSize], RandomReal[{0, 5}, 3]], {i, 1, 5}]], {k, 1, numFrames}];      I'd like to be able to set a time delay individually for each frame:               frameSetTimeDelaysInSeconds = RandomReal[{0,1}, numFrames];      Is this possible?


title: Enlarge the axes text

text: Plot[Sin[x^2], {x, 0, 3}, AxesLabel -> {"x value", Sin[x^2]}]      In the above code give a graph. In the graph the axes fonts are too small. My problem is that, how can I enlarge the axes text `x` and `x^2` without changing the basic.


title: Several functions in one RegionPlot with different grayscale

text: I try to plot the following, but something seems to be wrong in my code and I can't figure out how to fix it:               RegionPlot3D[       {        CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 0],        CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 1],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 2],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 3],         CountRoots[σq33[ω, V1, V2, V3], {ω, 0, Infinity} == 4]       },       {V1, 0, 50}, {V2, 0, 50}, {V3, 0, 100},       {GrayLevel[i, 0.5], {i, 0, 0.8, 0.2}},       Mesh -> None,        LabelStyle -> (FontSize -> 14)     ]      The number of roots in omega of the function `σq33` depends on the other Variables V1, V2 and V3. I would like to visualize that. The regions where `CountRoots` gives different values should be in different gray levels, all with an opacity of 0.5. I think the problem I have is that I do not know how to use `GrayLevel` to define different shades of gray for the different areas. And do you have an idea how to define the `CountRoots`-functions all in one, maybe with `Map` or something like that? Here is the `σq33`, in case it is necessary to answer the question:               σq33[ω_, V1_, V2_,        V3_] = (1/48 (Exp[-V1] + Exp[-V2]) (1 + Exp[-V3]) +         1/48 (Exp[-(V2 - V1)/2] - Exp[(V2 - V1)/2])/(Exp[(V2 - V1)/2] +             Exp[-(V2 - V1)/2]) ((Exp[-V1] - Exp[-V2] Exp[-V3]) - (Exp[-V2] -              Exp[-V1] Exp[-V3])) +         1/8 ((Exp[-V1] - Exp[-V2] Exp[-V3]) + (Exp[-V2] - Exp[-V1] Exp[-V3])) (-2 (Exp[-V1] +              Exp[-V2] Exp[-V3] + Exp[-V2] +              Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                Exp[-(V2 - V1)/2])/(ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                  Exp[-V1] Exp[-V3])^2)) +         1/2 ((Exp[-V1] - Exp[-V2] Exp[-V3]) - (Exp[-V2] -              Exp[-V1] Exp[-V3])) (-(Exp[-V1] + Exp[-V2] Exp[-V3] - Exp[-V2] -               Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +               Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +               Exp[-(V2 - V1)/                2]) (2 ω^2 - (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                  Exp[-V1] Exp[-V3])^2)/((ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                    Exp[-V2] + Exp[-V1] Exp[-V3])^2) (4 ω^2 + (Exp[-V1] +                    Exp[-V2] Exp[-V3] + Exp[-V2] + Exp[-V1] Exp[-V3])^2))) + ((Exp[-V1] -              Exp[-V2] Exp[-V3]) + (Exp[-V2] -              Exp[-V1] Exp[-V3])) ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +               Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                Exp[-(V2 - V1)/                 2]) ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] + Exp[-V1] Exp[-V3])^2 -                5 ω^2)/(6 (9 ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                     Exp[-V1] Exp[-V3])^2) (ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                     Exp[-V2] + Exp[-V1] Exp[-V3])^2)) + (Exp[-V1] + Exp[-V2] Exp[-V3] -                Exp[-V2] -                Exp[-V1] Exp[-V3])^2 ((Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                 Exp[-V1] Exp[-V3]) (-Exp[-(V1 + V2)/2 - V3] +                  Exp[-(V2 + V1)/2])/(Exp[(V2 - V1)/2] +                  Exp[-(V2 - V1)/                   2]) (11 ω^2 - (Exp[-V1] + Exp[-V2] Exp[-V3] + Exp[-V2] +                     Exp[-V1] Exp[-V3])^2)/(2 (ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                       Exp[-V2] + Exp[-V1] Exp[-V3])^2) (4 ω^2 + (Exp[-V1] +                       Exp[-V2] Exp[-V3] + Exp[-V2] +                       Exp[-V1] Exp[-V3])^2) (9 ω^2 + (Exp[-V1] + Exp[-V2] Exp[-V3] +                       Exp[-V2] + Exp[-V1] Exp[-V3])^2)))))


title: How to make TraditionalForm display the same in the Manipulate output as in a notebook?

text: I noticed that TraditionalForm does not display as nice in the Manipulate output as in normal notebook. Is there a way to make it look the same? Here is an example,               Manipulate[     TraditionalForm[-Derivative[2, 0][u][x, y]-Derivative[0, 2][u][x, y] == f[x, y]],      {z, None}     ]      and compare the output above to the same command, but without the Manipulate wrapper:               TraditionalForm[-Derivative[2, 0][u][x, y]-Derivative[0, 2][u][x, y] == f[x, y]]      Here is the output, side by side. (left side is the Manipulate output). ![enter image description here](http://i.stack.imgur.com/pdxGl.png) There might be an option to correct this inside Manipulate? Will keep looking. But meanwhile, any one knows why that is? btw, I found that by Rasterizing it, it looks close to the notebook, but need to work on the resolution little:               Manipulate[      Rasterize@       TraditionalForm[-Derivative[2, 0][u][x, y] -           Derivative[0, 2][u][x, y] == f[x, y]],      {z, None}      ]      ![enter image description here](http://i.stack.imgur.com/PzMG8.png) thanks


title: Computing a logarithmic function

text: Possibly this is a very lame question for this site. There is a function $f(n)=-\ln(a*n); \space \Bbb Z \to \Bbb R$, and I want to define $a$ for pairs of values. For example: $f_1(n_1)=15; f_1(n_5)=1.157$ $f_2(n_1)=454; f_2(n_8)=1.0042$ and so on. How can I write a function that could calculate $a$ values from the starting values?


title: Plotting - recursive

text: # Slightly clearer, hopefully: I would like to plot Solve[Normal[Series[E^(n x), {x, 0, n}]] == 0 for incrementally increasing n, and show all plots overlayed. Here is my effort with up to n=63 using this code: ![enter image description here](http://i.stack.imgur.com/oqfEc.gif) ...Very time consuming though, & I would really like to find a way of plotting it (& similar plots) up to any n without the labour-intensive copying & pasting.


title: Why won't SparseArray let me store values with the head List?

text: When you attempt to define a `SparseArray` with elements that have the head `List` it complains:               SparseArray[{1 -> {1, 2, 3}, 2 -> {"a", "b"}}]      > SparseArray::valnl: The value specified by the rule 1->{1,2,3} should not be > a List. >> >   >   >     SparseArray[{1 -> {1, 2, 3}, 2 -> {"a", "b"}}] >   Nevertheless (other) arbitrary expressions are accepted:               SparseArray[{1 -> foo[1, 2, 3], 2 -> bar["a", "b"]}]      ![enter image description here](http://i.stack.imgur.com/aW617.png) There does not appear to be any actual limitation of `SparseArray` that prevents it from storing `List` elements. In fact with a bit of fiddling we _can_ get `SparseArray` to hold `List` elements! First wrap the Lists an additional head so that `SparseArray` accepts them, then use `Part` to extract the first part of every element, essentially stripping the arbitrary extra heads (`foo`):               sa1 = SparseArray[{1 -> foo@{1, 2, 3}, 2 -> foo@{"a", "b"}}];          sa2 = sa1[[All, 1]];      We now have a `SparseArray` with `List` elements:               sa2 // Head     sa2[[1]] // Head     Head /@ Normal[sa2]     sa2["NonzeroValues"]      > >     SparseArray >   >     List >   >     {List, List} >   >     {{1, 2, 3}, {"a", "b"}} >   However if we try to use the `InputForm` of the expression (as input) it does not work:               ToString[sa2, InputForm] // ToExpression      > >     SparseArray[Automatic, {2}, 0, {1, {{0, 2}, {{1}, {2}}}, {{1, 2, 3}, > {"a", "b"}}}] >   Sadly this false equivalence breaks the use of `Save` and pattern-based manipulation of the object. Why would `SparseArray` be blocking the use of `List` when apparently any other head is accepted, and when there is internal support for `List` itself?


title: Computing the genus of an algebraic curve

text: How-to compute the genus of an algebraic curve in Mathematica ? In my case the algebraic curve is explicitly defined by a polynomial.


title: Asymptotic expansion, negative powers

text: The question was inspired by this discussion: How to expand a function into a power series with negative powers? I am interested in asymptotic behavior of a function at infinity:               f[r_]:=(0.04962 Exp[-2 r] (-1.000+r))/((0.06119+(Exp[-2 r])^(2/3))^2 r)      or (TeX) $$ f(r)=\frac{0.04962 e^{-2 r} (r-1.000)}{\left(\left(e^{-2 r}\right)^{2/3}+0.06119\right)^2 r} $$ Tried `Series[f[r],{r,0,10}]` for expansion in **_negative powers_** at infinity (as suggested) and got: $$ -\frac{0.04406}{r}+0.02146+0.02106 r+0.004405 r^2-0.001355 r^3-0.001205 r^4-0.0003607 r^5-\left(8.402\times 10^{-6}\right) r^6+0.00004149 r^7+0.00001982 r^8+\left(3.921\times 10^{-6}\right) r^9-\left(6.018\times 10^{-7}\right) r^{10}+O\left(r^{11}\right) $$ Seems like the function decays faster than $1/r^n$ and the expansion is meaningless. But what does the term $-\frac{0.04406}{r}$ mean then? The function is strictly positive at infinity and I am kinda confused by that. Does this mean that the asymptotic form of the function is _something_ plus the term $-\frac{0.04406}{r}$ which effectively gives the observed behavior? Can someone clarify it? How can one explain the term $-\frac{0.04406}{r}$?


title: Volumetric analysis from topological maps

text: I want to calculate the volume of fill required to level an area about the size of three foodball fields. The Department of Public Works in my city can provide me with topo data for the area. Their request form lists ArcView shapefile, AutoCAD.dwg, Geodatabase, and "other" data file formats, and JPEG, TIFF, and PDF map file formats. What kind(s) of files should I ask for? How do I calculate the volume of data required for an area I'm interested in? I don't know anything about this stuff. I would also like to estimate the number of trees, associated carbon dioxide sequestration, etc. for the area, and other things related to the wildlife in the area (based on some assumptions relevant to my area and the type of vegetation in the area). This additional question may not really be a _Mathematica_ question, but if there is something relevant in _Mathematica_ 's curated data, I would appreciate suggestions.


title: Calculations in sequence

text: I have a this calculation, as you can see it is doing a calculation on each list, from list 1 to list 4 of the datafile. My problem is that using Mapthread to do this calculation does not work because it does not do it stepwise. Is it possible to do these calculations in one go. example=datafile[[2 ;;, 1]] is a singe list of stock close price from a period of 500 days, looking like this: sample:               {4.40267, 4.85723, 8.80984, 4.62259, 6.74677, 3.41247, 2.3579, \     1.5767, 8.1023, 0.846309}          xt=Range[20]     In[81]:= d1 = CorrelationFunction[datafile[[2 ;;, 1]], #] & /@ xt          Out[81]= {0.999145, 0.998342, 0.997537, 0.996713, 0.995874, 0.995047, \     0.994209, 0.9934, 0.992535, 0.991635, 0.990724, 0.989826, 0.988893, \     0.98796, 0.987006, 0.986039, 0.985056, 0.984071, 0.983062, 0.982049, \     0.981015, 0.980023, 0.979034, 0.978088, 0.977124, 0.976173, 0.975284, \     0.974368, 0.973422, 0.972492}          In[86]:= d2 = CorrelationFunction[datafile[[2 ;;, 2]], #] & /@ xt          Out[86]= {0.998978, 0.997943, 0.996913, 0.995889, 0.994845, 0.993787, \     0.992737, 0.991701, 0.990673, 0.989631, 0.988578, 0.987528, 0.986518, \     0.985486, 0.984453, 0.983412, 0.982381, 0.981336, 0.98028, 0.97924, \     0.978187, 0.977157, 0.976174, 0.975197, 0.974231, 0.97327, 0.97235, \     0.971439, 0.970547, 0.969652}          In[92]:= d3 = CorrelationFunction[datafile[[2 ;;, 3]], #] & /@ xt          Out[92]= {0.999266, 0.998475, 0.997678, 0.996881, 0.996119, 0.995341, \     0.994551, 0.993777, 0.992971, 0.992156, 0.991314, 0.990456, 0.989605, \     0.988753, 0.98795, 0.98713, 0.986287, 0.985381, 0.984481, 0.983552, \     0.982617, 0.981703, 0.980813, 0.97997, 0.979149, 0.978341, 0.977537, \     0.976723, 0.975906, 0.975078}          In[90]:= d4 = CorrelationFunction[datafile[[2 ;;, 4]], #] & /@ xt          Out[90]= {0.998632, 0.997179, 0.995736, 0.994285, 0.99281, 0.991288, \     0.989771, 0.988194, 0.986626, 0.985064, 0.983506, 0.981978, 0.980482, \     0.978987, 0.977529, 0.976089, 0.974685, 0.973293, 0.971882, 0.970521, \     0.969074, 0.967699, 0.966367, 0.965024, 0.963719, 0.962478, 0.961284, \     0.960064, 0.958861, 0.957659}


title: Filtering pixels of a certain color

text: What is the best way to filter an image so that only the pixels close to a certain color are left? I've downloaded some satellite images from the web where a specific pixel color corresponds to a some type of crop. Thus I would like to filter out with Mathematica those pixels that are specifically for that color so I can next run ComponentMeasurements to obtain the area covered by those pixels, so I was trying to figure out what function to use or build that would just return an image with the pixels that match or are truly similar to the color provided.