Problem with equation solving using Solve

I understand that these kinds of questions may be a bit overdone but I can't for the life of me figure out what's wrong with this piece of code.                   Solve[df == (Sqrt[2*Pi]*s)^(-n) &&          cf == 0 && af*s^3 + bf*s^2 +          cf*s + df ==          1/(E^(1/2)*(Sqrt[2*Pi]*s)^n) &&          ak*s^3 + bk*s^2 + ck*s + dk ==          1/(E^(1/2)*(Sqrt[2*Pi]*s)^n) &&          3*ak*s^2 + 2*bk*s + ck ==          3*af*s^2 + 2*bf*s + cf &&          ak*(2*s)^3 + bk*(2*s)^2 +          ck*(2*s) + dk == 0 &&          3*ak*(2*s)^2 + 2*bk*(2*s) + ck ==          0 && (2*Pi^(n/2)*((af*s^4)/4 +          (15*ak*s^4)/4 + (bf*s^3)/3 +          (7*bk*s^3)/3 + (cf*s^2)/2 +          (3*ck*s^2)/2 + df*s + dk*s))/         Gamma[n/2] == 1/2, {af, bf, cf, df,          ak, bk, ck, dk}]      It outputs {} and i can't understand why.


Is there a built-in function which detects singularities in a function?

Given a function `f[x]` and a region M in the complex x-plane, how can I find singularities of `f` in this region, i.e., issue a command to _Mathematica_ which returns the type of singularity and its parameters? Let me be more specific   1. discontinuities (jumps)   2. poles   3. branch points Examples               f[x_] := Sin[x] Sign[Cos[x]]     g[x_] := 1/(a - x)^2     h[x_] := Sqrt[x + b]        **EDIT 11.09.14**   The restriction to real x in my first version of the text was not a good idea. I have changed it.


Switching the ordinate and abscissa causes problem in `ParametricPlot`

I have a function that plots properly in `PolarPlot`, but I'd like to plot it in `ParametricPlot` and then switch the y and x values, or ordinate and abscissa. It doesn't work for my function, but I'm not sure if it's just my function or some other subtle problem:               r[phi_] := (6*(Cos[phi]^5)/(2*Pi))^0.5;     PolarPlot[r[phi], {phi, 0, Pi}]     new[x_] := CoordinateTransform["Polar" -> "Cartesian", {Re[r[x]], x}];     ParametricPlot[{new[x], x}, {x, 0, Pi}]     ParametricPlot[{x, new[x]}, {x, 0, Pi}]      Generates: ![enter image description here](http://i.stack.imgur.com/SGbzu.jpg) ![enter image description here](http://i.stack.imgur.com/vuKPj.jpg) ![enter image description here](http://i.stack.imgur.com/tHFEJ.jpg) The final plot doesn't contain anything, and no errors or warnings are output.


Overwriting first line of large file

As mentioned, I wish to read the first line of a file, and if needed, overwrite it with a new string. The aim is to have a CSV with a list of possible elements. Example:               Adding the elements: 5 A, 6 B, and 7 C to a blank CSV:     A B C     5 6 7     Adding 4 A, 9 D:     A B C D     5 6 7     4 0 0 9     Adding 2 B, 7 E     A B C D E     5 6 7     4 0 0 9     0 2 0 0 7      Rewriting the file is okay for small files, but the files are expected to grow to sizes of hundreds of MB, so repeatedly overwriting the entire file is not practiceable, since the entries are preferably done quickly. How would one go about overwriting only the first line of the file? Reading the first line is possible from http://mathematica.stackexchange.com/questions/5179/how-to-read-data-file- quickly# _=_, but what about writing?


how could I repalce Sqrt[x^2+y^2+z^2] back to r

do a calculation in mathematica               r = Sqrt[x^2+y^2+z^2]          D[D[E^(I (-k r + t \[Omega]))/r, x], y]      but how could I get back to repalce Sqrt[x^2+y^2+z^2] back to r the result is: $$ -\frac{k^2 x y e^{i \left(t \omega -k \sqrt{x^2+y^2+z^2}\right)}}{\left(x^2+y^2+z^2\right)^{3/2}}+\frac{3 i k x y e^{i \left(t \omega -k \sqrt{x^2+y^2+z^2}\right)}}{\left(x^2+y^2+z^2\right)^2}+\frac{3 x y e^{i \left(t \omega -k \sqrt{x^2+y^2+z^2}\right)}}{\left(x^2+y^2+z^2\right)^{5/2}} $$


Get the name of a symbol passed to a function

I'm trying to get the name of a symbol passed to a function with this:               f[x_] := {SymbolName[x], x}     SetAttributes[f, HoldFirst]     x = 5;     f[x]      But `x` is being evaluated anyway:               SymbolName::sym: Argument 5 at position 1 is expected to be a symbol. >>     {SymbolName[5], 5}      What am I missing here?


Mapping with Trace[]

As part of some data anaylsis, I am using the function Trace to give me the name of an array of data, which I then use to label my plots. eg. my data array is called r1 so I run:               ToString@((Trace[r1])[[1]])      which simply returns the string "r1". All fine and dandy. The problem arises when I try to do this for a list of data arrays, I write:               Trace[#]&/@{r1,r2}      which I expect to give me the list {"r1","r2"}. Instead I get {{},{}}. What am I doing wrong? Any help will be much appreciated!


Dynamic graphics are less responsive inside a Manipulate

I have some code which displays a `GraphPlot` and allows the user to click on any vertex in the graph to display some information about that vertex in a popup window. There is two-way highlighting between the popup and the vertex, so that if the user hovers over either the vertex or the popup window, both the vertex and the popup will be highlighted (the vertex by changing size and the popup by changing colour). I do this by defining a `VertexRenderingFunction` for the graph plot which uses `Module` to create a unique symbol for each vertex. This symbol is set to `True` whenever the mouse is over the vertex or the popup window, and the dynamic highlighting is determined by the value of the symbol. This works okay (though I'd be interested in better ways to accomplish the same effect). However, as soon as I put the `GraphPlot` inside a `Manipulate`, the highlighting becomes rather sluggish, even if the `Manipulate` is not changing the plot in any way. I don't understand why that happens. Here's a minimal working example:               (* create some data *)     data = Thread[RandomChoice[Range[200], 350] -> RandomChoice[Range[200], 350]];          (* define the vertex rendering function *)     vrf := Module[{mo},        PopupWindow[         Dynamic[          mo = CurrentValue["MouseOver"];          {PointSize[Dynamic[If[mo, 0.03, 0.01]]], Point[#1]}],         Dynamic[          mo = CurrentValue["MouseOver"];          Panel["Popup Window Text", Background -> Dynamic[If[mo, Pink, White]]]]         ]] &;          (* graph plot *)     gp = GraphPlot[data, VertexRenderingFunction -> vrf]      This works nicely. But if I do this:               Manipulate[gp, {x, 0, 10}, TrackedSymbols :> {x}]      it is much less responsive. Can anyone tell me why this happens, and more importantly how to prevent it? I'm using version 8.0.4 by the way. **NB** The first argument of the `Manipulate` in my example is deliberately independent of `x`. The slider control is nothing to do with the problem, it is just there to make a valid Manipulate expression. I have used `TrackedSymbols :> {x}` to make doubly certain that Manipulate isn't tracking any symbols inside the GraphPlot. In my real application the `Manipulate` does useful things, but I realised as I stripped the code down that merely being inside a `Manipulate` affects the responsiveness of the plot, even if the `Manipulate` doesn't change the plot in any way.


Problem with cross product of two columns

I am trying to perform a cross product of two "Columns" which I expect to give me a column too: > Cross[{{a}, {b}, {c}}, {{x}, {y}, {z}}] but it gave me an error: > Cross::nonn1: The arguments are expected to be vectors of equal length, and > the number of arguments is expected to be 1 less than their length. any idea why this is happening ?


Discrete sampling of interpolating function returned by NDSolve

When solving an ODE with NDSolve, Mathematica returns an interpolation function. I need a discrete sampling of this function however. Naively, I can write this as (example):               slv = f[t]/. NDSolve[f'[t] == -f[t], f[t], {t,0,10}][[1]];     result = Table[{T, slv/.t->T}, {T,0,10,0.1}];      This is very slow for large times and fine sampling, and I have to do this for a large number of functions. But in principle, Mathematica must already store a discretized representation of the function for the interpolation function. Is there a way to access this? Or do you have suggestions on how to make the code above faster? Thanks!


How can I draw a polygon from a set of angles?

In recreational mathematics, polytans are polygons formed by edge-connecting isosceles right triangles. Order- _n_ polytans are those constructed from _n_ such triangles. My question is this: Given a set of _n_ angles and an N x N grid, how do I draw a graph using a set of angles? I am trying to find if the angles form the perimeter of a polytan (i.e., given a starting point on the plane, does progressively iterating through the angles get me back to the point of origin?). For example, given these three sets: {{270, 315, 315}, {315, 270, 315}, {315, 315, 270}}, the output would show two isosceles right triangles: {270, 315, 315} and {315, 315, 270}, and one non-polygon: {315, 270, 315}, as seen in the image below. In the image, the initial reference line is {{0,0}->{0,1} (on the y-axis), and the point of origin is {0,1}. ![enter image description here](http://i.stack.imgur.com/UWuss.png) I need the constructions to be graphs so that I can check whether two polytans of the same order are identical, but just in different orientations (like the two triangles in the image). Vertex count, vertex degree, edge-connectedness, etc., would also be useful.


How to specify assumptions before evaluation?

If I request mathematica evaluate an integral for me, I'll often get a more general `ConditionalExpression` than I want. Example :               Clear[ii, u, z, l, jj]     ii = Integrate[ 1 / Sqrt[z^2 + u^2], {z, -l, l}]      > >     ConditionalExpression[ -Log[-l + Sqrt[l^2 + u^2]] + Log[l + Sqrt[l^2 + > u^2]], >                                            Re[u/l] != 0 || Im[u/l] >= 1 || > Im[u/l] <= -1] >   I can reduce this after the fact with something like:               jj = FullSimplify[ii, u > 0 && l > 0 && Element[ u | l, Reals] ]      > >     Log[(u^2 + 2 l (l + Sqrt[l^2 + u^2]))/u^2]   >   but I'd imagine it should often simplify the calculations if I could provide the assumptions up front, especially the obvious ones like restricting various variables to the domain of reals. Is there a way to do this?


Excluding an interval of parameters from Integrate

I'd like to compute an integral that depends on a parameter, but I'd like to exclude an interval from the computation. For concreteness, say I want to compute               Integrate[f[x,z],{x,-a,a}]      but I would like to specify that z is a complex number _not_ in the real interval [-a,a]. Any thoughts? If I let the integral run, I get a conditional expression that I think is correct, but I'd like to specify the exclusion ahead of time if possible. Thanks!


How to add a condition to a formula so that it will not appear at the result?

Sometimes I have very long and complicated equations, when I evaulate the equations for example taking derivative or integral there will be several conditions with the answer. My question is that; is there any way that I enter the conditions at the begining of the program so that so that it will not appear in the evaluation result? I will give a simple example:               pdf = x^(L-1)/( γ^L Gamma[L]) Exp[(-x)/γ];     Re[L] > 0;          Integrate[ pdf, {x, 0, γ}]      > >     ConditionalExpression[ (Gamma[L]-Gamma[L,1])/(Gamma[L]),  Re[L] > 0 ] >   in the above example even if I write the condition which is `Re[L] > 0`, it will appear again at the result of evaluation.


Telling mathematica that something is an integer

Is it possible for me to tell mathematica something is an integer? like if I typed               Sin[n Pi]+Cos[n Pi]      it would tell me it equals 1 for even n and -1 for odd n? This would really help me check my answers when trying to find Fourier Series (I am just learning them now)


How can I say that all quantities need to be positive (and real)?

Can you say at the beginning of a script in Mathematica that you want all the quantities to be positive (and real)? So that in all calculations, only the real values of these quantities will be considered (by calculations and by plotting) I want to do this because I want to optimize a free energy by finding the best length quantities. But then I will find answers with negative or imaginary length quantities.Also when I make a 3Dplot of the free energy as a function of two of these quantities, Mathematica plot the imaginary values. Update: An example is: R1 is defined as followed:               R1[a_,l_] =        1/3 (-((l π OppC[α]^2)/VolS[α]) + (2^(1/3) l^2 π^2 OppC[α]^4)/(VolS[α] (-2 l^3 π^3 OppC[α]^6 +        27 v VolS[α]^2 + 3 Sqrt[3]Sqrt[-4 l^3 π^3 v OppC[α]^6 VolS[α]^2 +        27 v^2 VolS[α]^4])^(1/3)) + 1/(2^(1/3)VolS[α]) (-2 l^3 π^3 OppC[α]^6 +        27 v VolS[α]^2 + 3 Sqrt[3]Sqrt[-4 l^3 π^3 v OppC[α]^6 VolS[α]^2 + 27 v^2 VolS[α]^4])^(1/3));      Then I want to Plot R1:               Plot3D[R1[α, l], {α, 0, 0.5*π}, {l, 0, 10}].       But by plotting, also imaginary values of R1 are plotted. What do I have to do that Mathematica does not plot these values?


Combine InputAlias with InputString to parse expressions from a string

My knowledge of low-level notebook programming is very limited so I would be very grateful for any input regarding the following issue: I would like to define an input alias (via `InputAliases`) that evaluates               parse[InputString[]]      _in-place_ (like selecting it and then performing _Menu_ → _Evaluation_ → _Evaluate in Place_ or `Cmd` \+ `Return`). The function `parse` will translate my textual input into an expression (and insert it at the current cursor position). Currently, I am using the following alias,               SetOptions[EvaluationNotebook[],         InputAliases->{"parse"->RowBox[{"parse","[","InputString","[","]","]"}]}]      and the workflow looks like this   1. `ESC` `parse` `ESC` to produce `parse[InputString[]]`   2. Press `Ctrl` \+ `.` a few times to select `parse[InputString[]]`   3. Evaluate in place via `Cmd` \+ `Return`   4. Type something into the input field and press `Return` Basically, I would like to get rid of steps 2 and 3. I would appreciate any other solution if the desired behavior cannot be achieved using `InputAliases`. I would also be more than happy if an `InputField` could be used instead of `InputString`.


How can I make an X-Y scatter plot with histograms next to the X-Y axes?

I just saw a nice plot there: ![enter image description here](http://i.stack.imgur.com/gjON3.png) How could I implement that in Mathematica — by which I mean the plot structure, not so much the styling.


3D visualization of 4D object data

I have some paired data here {{x1,y1},...{x_n,y_n}} (Download link) which represents {frequency, amplitude} of a spatial object surface mesh. Its quite a lot of cells and data as you can see in the histogramms, x frequency, y amplitude, z number of cells with specific frequency and data bin range. ![enter image description here](http://i.stack.imgur.com/vuJl3.jpg) ![enter image description here](http://i.stack.imgur.com/R3LzF.jpg) Now this data gets plotted with to visualize distinct spots of the sample surface with different amplitude by different colors. Most of the frequency dynamics happens between 0.3-4.9               ArrayPlot[gridmatrixpair, Mesh -> False, ColorFunction -> (Which[          0.3 < #[[1]] < 4.9 && 1*10^1 > #[[2]] > 1*10^0, Pink,          0.3 < #[[1]] < 4.9 && 1*10^2 > #[[2]] > 1*10^1, Gray,          ...      AspectRatio -> 2/7]       ![enter image description here](http://i.stack.imgur.com/JBzdf.jpg) or different frequency in narrow amplitude range               ArrayPlot[gridmatrixpair, Mesh -> False, ColorFunction -> (Which[          0.3 < #[[1]] < 0.8 && 1*10^9 > #[[2]] > 1*10^7, Pink,          0.8 < #[[1]] < 1.3 && 1*10^9 > #[[2]] > 1*10^7, Gray,          ...          True, White] &), ColorFunctionScaling -> False,       AspectRatio -> 2/7]       ![enter image description here](http://i.stack.imgur.com/mtNaB.jpg) I was wondering what would be a solution to show a combined spatial frequency and amplitude distribution in one picture. What I think of is something like the 3rd picture but this 2D picture is actually in a 3DHistogram like picture where the bar height represents the amplitude and bar color frequency, so actually 3D visualization of 4D data. Or represent frequency from lightblue to darkblue, amplitude from lightred to darkred and then both colors are mixed according to RGB to represent the mixture by green, but probably not so good visual contrast as this data covers 4-5 ranges that need to be covererd. One could also probably use simply the 3rd picture and project it on the xy-plane of a ListPlot3D (I think MM can do this), and then take the amplitude as z-data. I have no starting point and no big overview about MM, I'm looking more for a tip what is the right direction which gives a good visual contrast for those 4-5 ranges.


Discrete 3D Plot with date on one axis

1) How do I plot the following data in 3D (large data, only a part of it is used here):               {      {"date", "v1", "v2"},      {{2000, 6, 16, 0, 0, 0.}, 10.4324, 11.084},      {{2000, 6, 30, 0, 0, 0.}, 9.75499, 11.02},      {{2000, 7, 14, 0, 0, 0.}, 10.0905, 10.932},      {{2000, 7, 28, 0, 0, 0.}, 10.2406, 11.249},      {{2000, 8, 11, 0, 0, 0.}, 10.1241, 11.411},      {{2000, 8, 25, 0, 0, 0.}, 9.92124, 11.4},      {{2000, 9, 8, 0, 0, 0.}, 8.63775, 11.566},      {{2000, 9, 22, 0, 0, 0.}, 8.52399, 11.507},      {{2000, 10, 6, 0, 0, 0.}, 9.09311, 11.635},      {{2000, 10, 20, 0, 0, 0.}, 8.68255, 11.626},      {{2000, 11, 3, 0, 0, 0.}, 8.19321, 11.696},      {{2000, 11, 17, 0, 0, 0.}, 9.47059, 11.296},      {{2000, 12, 1, 0, 0, 0.}, 9.75926, 11.469},      {{2000, 12, 15, 0, 0, 0.}, 10.0035, 11.343},      {{2000, 12, 29, 0, 0, 0.}, 9.5563, 10.946},      {{2001, 1, 12, 0, 0, 0.}, 9.66618, 10.67},      {{2001, 1, 26, 0, 0, 0.}, 9.57756, 10.57},      {{2001, 2, 9, 0, 0, 0.}, 9.47097, 10.33},      {{2001, 2, 23, 0, 0, 0.}, 8.86714, 10.11}      }       2) I want to see how data evolves as time changes. How do I use `Manipulate` to do this?


How do I make a log plot where the plot is logarithmic in the distance from the X-Axis (including negative values)?

For example, if I were to do a plot of `Sin[x]`, I would get what looks like a Log plot of `Sin[x]`, with another log plot of `-Sin[x]` that has been flipped upside down and placed underneath the first one, in this way, the plot is logarithmic in distance from the x-axis, and can show both positive and negative values.


Visualization: elliptical insights into data sets…

I was recently reading the following paper on visualization techniques using ellipses to gain statistical insights. Elliptical visualization for looking at correlations has briefly been touched on this board as well. Elliptical Insights: Understanding Statistical Methods through Elliptical Geometry. There are a couple of plots in the paper on quickly plotting correlations between complex data that I found quite useful and would like to replicate them. Having a function to visualize complex correlations would be useful to a lot of folks… However, my skills in MMA are lacking a bit... ![Scatterplot Matrices showing data, 68% data ellipses and regression lines](http://i.stack.imgur.com/XJz6R.png) ![enter image description here](http://i.stack.imgur.com/lnsY4.png)


Can Mathematica check if two expressions give the same output for integer input?

Let me give the background for this question. I'm using WebAssign to assign homework problems, and WebAssign has a built-in mechanism which can grade problems using Mathematica commands. For instance, if the solution to a problem is $e^{x+y}$ then it is possible to use the Simplify command to ensure that $e^x e^y$ is marked as correct. I'm currently assigning problems on Fourier series, and expressions like $\cos(n \pi)$ occur frequently. It is fairly standard practice to rewrite $\cos(n \pi)$ as $(-1)^n$, and I want these two expressions to be treated as equivalent (as well as similar expressions for $\cos(n \pi /2)$, etc.) The problem is that these expressions are only equal on the integers, and so Mathematica has no reason to believe they are the same. I suppose I could just write some code which plugs in the first hundred integers and checks to see if the values are the same, but I'm wondering if there's a more elegant solution.


Simultaneous Equation Solving Under Nonnegative and Bounding Conditions

I have nonlinear equations to solve parametrically;               PG = 100;          p1 = 0.8;          p2 = 0.2;          Solve[C1 - 10 + PG/2 + GC1 + GL1 == 0 &&        C2 - 15 + PG/2 + GC2 + GL2 == 0 && GL1 - fd (a1) t 10 == 0 &&        GL2 - fd (a2) t 15 == 0 &&        GC1 - (t (1 - fd) 25 - PG) ((p1)/((p1) + (p2))) == 0 &&        GC2 - (t (1 - fd) 25 - PG) ((p2)/((p1) + (p2))) ==         0 && (0.3/GL1) - (0.5/C1) - (0.3/GC1) - (0.4/PG) ==         0 && (0.3/GL2) - (0.5/C2) - (0.3/GC2) - (0.4/PG) == 0 &&        GC1 - 4 GC2 == 0, {C1, C2, GC1, GC2, GL1, GL2, fd, a1, a2, t}]      I do get 8 roots for this problem. However, for more complex solvings of this model (change numeric values - 15,10 to alpha, beta, gamma) I do get no more memory error. To avoid that I want to put some conditions on the variables since all roots are not meaningful and it takes time+memory to calculate it. Ex: a1 > 0, a2 > 0, 0 $\leq$ fd $\leq$ 1, C1 C2 takes positive values. I want to solve under these or more conditions. How to put these nonnegativity and bounding conditions for variables in the mathematica solve command? At least if I could put nonnegativity conditions I would get rid of the negative roots. Does it matter if I use Reduce instead ? I would appreciate your comments and your help.


Export MatrixPlot graphics to PDF

I am trying to export a plot generated by `MatrixPlot` to PDF but am having problems with the way the exported PDF is rendered.                 mPlot = MatrixPlot[length,        Epilog -> {Cyan,          MapIndexed[If[#1 != 0, Text[#1, Reverse[#2 - 1/2]]] &,           Reverse[number], {2}]}, Mesh -> True,        FrameTicks -> {{Table[i, {i, 9}],           MapIndexed[{First[#2], regionCodes[[#1]]} &,            Table[i, {i, 9}]]}, {Table[i, {i, 9}],           MapIndexed[{First[#2], Rotate[regionCodes[[#1]], 90 Degree]} &,            Table[i, {i, 9}]]}}, ColorFunctionScaling -> False,        PlotRange -> {Min[length], Max[length]}]      The matrices `length` (plotted as shades of gray in the figure below), `number` (shown as the cyan numbers in the figure below), and `regionCodes` have the following values               length = {{0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0.079774, 0.0545131,         0.0484267, 0.0614324, 0.0627509, 0.0572262, 0.0424639, 0}, {0, 0,         0.0600802, 0.100418, 0.0615561, 0.0737833, 0.0732888, 0.0624553,         0}, {0, 0, 0, 0.0740108, 0.0559982, 0.0666054, 0.0749018,         0.0493431, 0}, {0, 0, 0, 0, 0.0774839, 0.0554172, 0.0564699,         0.0491287, 0}, {0, 0, 0, 0, 0, 0.0798436, 0.0643044, 0.0606039,         0}, {0, 0, 0, 0, 0, 0, 0.107009, 0.0713126, 0}, {0, 0, 0, 0, 0, 0,         0, 0.0951722, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}     number = {{0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 37, 53, 21, 778, 1064, 228,         15, 0}, {0, 0, 27, 40, 761, 1164, 272, 21, 0}, {0, 0, 0, 7, 331,         507, 125, 9, 0}, {0, 0, 0, 0, 5935, 12430, 2917, 245, 0}, {0, 0, 0,         0, 0, 10665, 4323, 393, 0}, {0, 0, 0, 0, 0, 0, 664, 90, 0}, {0, 0,         0, 0, 0, 0, 0, 7, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}     regionCodes = {"New England", "Middle Atlantic", "East North Central",        "West North Central", "South Atlantic", "East South Central",        "West South Central", "Mountain", "Pacific"}      This is `length//MatrixForm` ![enter image description here](http://i.stack.imgur.com/RDYJ0.png) And this is `number//MatrixForm` ![enter image description here](http://i.stack.imgur.com/bTfpA.png) The plot looks like this when shown in Mathematica ![enter image description here](http://i.stack.imgur.com/gO0DL.png) But the exported PDF is rendered as follows (shown in OS X Preview) ![enter image description here](http://i.stack.imgur.com/NAOLh.png) There is a lot of shading and (and anti-aliasing?) going on (it shouldn't!). The only solution I have come up with is to rasterize the plot before exporting it. It does the job, but I don't consider it very elegant.               Export["regionIBD_MatrixPlot.pdf", Rasterize[mPlot, ImageResolution -> 600], ImageSize -> Full]      The funny thing is that if I export it as TIFF, it renders correctly. Is there a way to export the plot as a vector graphics and not as a bitmap?


Partial row reduction of a matrix

I have an $m\times n$ matrix (presumably of full rank) with $m>n$, and I would like to row reduce it, but leave the last column unreduced; that is, I want to get output on the form $\pmatrix{ 1 & 0 & 0 & \ast \\\ 0 & 1 & 0 & \ast \\\ 0 & 0 & 1 & \ast \\\ 0 & 0 & 0 & \ast \\\ 0 & 0 & 0 & \ast}$ instead of $\pmatrix{ 1 & 0 & 0 & 0 \\\ 0 & 1 & 0 & 0 \\\ 0 & 0 & 1 & 0 \\\ 0 & 0 & 0 & 1 \\\ 0 & 0 & 0 & 0 }$ which is what RowReduce gives me. I can't seem to mangle RowReduce into doing it, and I would really like to avoid manually implementing the algorithm. Is there some nice way to do this? Thanks in advance for any help you can give me.


Evaluate an ODE for several values of a coefficient and draw all the solutions in one plot

I want to draw one plot showing all the solutions the following ODE with different values of `N`. How can i do it?               s = NDSolve[{2 y'''[x] + (y[x]*y''[x]) == 0,                   g''[x] + (0.5****N***y[x]*g'[x]) == 0,                   g[0] == y[0] == 0, y'[0] == 0, y'[8] == 1, g[12] == 1}, {y, g}, {x, 0, 12}];          Plot[Evaluate[{g[x]} /. s], {x, 0, 12}, PlotStyle -> Automatic]


Factoring a quintic

I am trying to prove that a quintic polynomial, $p(x) = A5 x^5 + A4 x^4 + A3 x^3 + A2 x^2 + A1 x + A0$, which admits at most three real roots. Unfortunately Descartes' rule of signs does not help, since I have 5 sign changes. The polynomial's coefficients (the $An$ in the above expression) depend on a number of parameters, and after assigning numerical values to the parameters, _Mathematica_ factors the polynomial into the product of either   * three monic linear polynomials and a quadratic polynomial with negative discriminant   * one monic linear polynomial and two quadratic polynomials with negative discriminant which confirms what I think. Since _Mathematica_ can factor the quintic when the coefficients are numerical, I wonder if that implies it can also factor the quintic when expressed symbolically. If this is the case, how can I ask _Mathematica_ to do it?


PlotMarkers don't change colour for different lines

I have a set of data and several function operating on the same data, that I wish to plot together in a `ListPlot`. I need different `PlotMarkers` for each function to visualise the data. Because the data is quite closely spaced, I specified the number of markers using `Mesh` in the way I found here: Custom Intervals of Markers So I have the following:               a = Table[ii, {ii, 0, 2 \[Pi], 0.01}];     b = Sin[a];     c = Sin[a + \[Pi]/4 ];          ListPlot[       {Transpose[{a, b}],        Transpose[{a, c}]       },      PlotMarkers -> Automatic,      Joined -> True,      Mesh -> 20]      However, the `Mesh` command suddenly makes all markers the same shape and colour, so this is what I get out: ![enter image description here](http://i.stack.imgur.com/sa7Yf.png) How can I make sure that the `PlotMarkers`' colour and shape remain unchanged while being able to specify the number of markers in the plot? I'm using Mathematica 9.


Menu commands on Palettes and other windows without menu bars?

In the Version 10 interface, at least by default, there is no longer a common menu bar in a separate window, and menus appear to be localized to individual Notebook windows. If I select a Palette and attempt to use the menu in an adjacent Notebook, specifically **Generate Notebook from Palette** , the Palette loses focus and that menu item is disabled.   1. Can I restore the common menu bar from earlier versions?   2. If not what is the fastest and simplest way to apply these commands?   3. When is the **Generate Notebook from Palette** item not disabled? I have been unable to use it.


Dynamic Programming with delayed evaluation

By using dynamical programming, we can save intermediate steps for recursive relations, as in               f[n_]:= f[n] = f[n-1] + f[n-2]      However, this only stores definitions for explicit values of `n`. But I need to be able to store _function definitions_ , where the number of parameters of the function depends on each step. More specifically, I have something like $$ t^{a_1 \cdots a_n} = A \, t^{a_1 \cdots a_{n-2}} + B \, t^{a_2 \cdots a_n} \\\ t^a = C^a \\\ t^{ab} = D^{ab} $$ Where all $a_i$ are indices with unspecified values. This recursive definition allows me to express any $t^{a_1 \cdots a_n}$ as a combination of $C$'s and $D$'s. It's easy to implement this in mathematica:               t[a_]:= c[a]     t[a_,b_]:= d[a,b]     t[a__]:= A t@@Most[Most[{a}]] + B t@@Rest[{a}]      but for high $n$, calculation times become very long (and especially because my function is a bit more complicated than this). This is where we normally would use dynamic programming, something like:               t[a__]:= t[a] = A t@@Most[Most[{a}]] + B t@@Rest[{a}]      but this is not what we need, because if I execute               t[a,b,c]      it only makes a definition for `a`, `b` and `c` literally, meaning that `t[b,a,c]` will have to be recalculated recursively. This is because it is stored as `Set`, and not a `SetDelayed`:               t[a,b,c] = A c[a] + B d[b,c]      What I would need is some kind of magic dynamic programming that stores function definitions as in               t[a__]:= Magic.... =A t@@Most[Most[{a}]] + B t@@Rest[{a}]      such that when I execute               t[a,b,c]      it stores               t[a_,b_,c_] := A c[a] + B d[b,c]      etcetera. I've looked into Leonid's answer for this question, but I can't easily see how to adapt it for a growing number of arguments. Any ideas? Many thanks in advance! **EDIT** Thanks to Leonid's answer, I now understand a bit how this can be solved. Unfortunately, the way I'd need it, is a bit more complicated. I have several function definitions, with `Condition`, `PatternTest`, `Optional` and next to the recursive ('growing') variables I also have some that aren't. At first I thought I'd figure it out myself based on Leonid's answer (hence the accept), but I didn't. The idea is to make a wrapper `memoize`, which I wrap around my function definition such that it memorises the function definitions. An example in pseudocode:               memoize[         t[dot[a__], b_?EvenQ, c_:1]/;b!=c := .... some recursive function of t ...     ]      The first thing I tried is to retrieve all patternames, and replace them with `Unique[]` ones:               ClearAll@memoize     SetAttributes[memoize, HoldAllComplete]     memoize[expr_SetDelayed] :=         (* first we retrieve the lhs and rhs *)         With[{funcLHS = Hold[expr] /. Hold[SetDelayed[x_, y_]] :> Hold[x] ,                funcRHS = Hold[expr] /. Hold[SetDelayed[x_, y_]] :> Hold[y]},             (* next we retrieve the names of the patterns used *)             With[{patternNames = First /@ Cases[funcLHS, _Pattern, Infinity]},                 (* we make some locally scoped patterns *)                 With[{varsExt = Table[Unique[], {Length[patternNames]}]},                     (* and we express the lhs and rhs in function of the former locally scoped patterns *)                     With[{lhs = funcLHS /. Rule @@@ Transpose[{patternNames, varsExt}],                            rhs = funcRHS /. Rule @@@ Transpose[{patternNames, varsExt}]},                             {lhs,rhs}/.{Hold[x_],Hold[y_]}:>SetDelayed[x,y]         ]]]]      And this works, but it doesn't do anything useful. Now I would need to replace the central part with Leonid's answer somehow, which means I have to inject `vars` into `lhs` and `rhs`, with the additional difficulty that `Length[vars]` won't equal `Length[varsExt]`. So this is what I tried:               ClearAll@memoize     SetAttributes[memoize, HoldAllComplete]     memoize[expr_SetDelayed] :=         With[{funcLHS = Hold[expr] /. Hold[SetDelayed[x_, y_]] :> Hold[x] ,                funcRHS = Hold[expr] /. Hold[SetDelayed[x_, y_]] :> Hold[y]},             With[{patternNames = First /@ Cases[funcLHS, _Pattern, Infinity]},                 With[{varsExt = Table[Unique[], {Length[patternNames]}]},                     With[{lhs = funcLHS /. Rule @@@ Transpose[{patternNames, varsExt}],                            rhs = funcRHS /. Rule @@@ Transpose[{patternNames, varsExt}]},                              {lhs, Hold[                             With[{vars = Table[Unique[], {Length[{#}]}] & /@ varsExt},                                 With[{pts = (Pattern[#1, _] &) /@ vars},                                     {lhs/.MapThread[ Pattern[#1, _] -> Sequence @@ (Function[x, Pattern[x, _]] /@ #2) & , {varsExt, vars} ]                                     ,                                     rhs/.MapThread[ #1 -> Sequence @@ #2 & , {varsExt, vars} ]                                     }/.{Hold[x_],Hold[y_]}:>Set[x,y] ;                                     lhs/.x_Pattern:>x[[1]]                             ]]]                          } /. {Hold[x_], Hold[y_]} :> SetDelayed[x, y]          ]]]]      But the pattern replacing on `lhs` doesn't work, and it doesn't take care of `Condition`, `Optional`and `PatternTest`. So I'm totally stuck, although I have the feeling that it's only a few changes to make it work..


Mathematica plotting help (plotting a complex fourier series).

How would I plot the following in Mathematica? $ \displaystyle\sum_{n=2}^{10} \bigg(\dfrac {4ine^{inx}(-1)^n}{(n^2 - 1)^2} - \dfrac{4in e^{-inx}(-1)^n}{(n^2 - 1)^2} \bigg) $ Thanks.


Summation with jump indices like 1,4,6,9?

I is easy to enter $ \sum_{s=1}^{n}k(s) $ But how can I enter $ \sum_{s=1,3}k(s) $ ? When I try it, Mathematica says               Syntax::sntxi: Incomplete expression; more input is needed .      Also the following didn't work. $\sum_{s=1,3}^{3}k(s)$


list manipulation

I have a list like the following:                {{1, 3}, {2, 5}, {3, 6}, {2, 4}}      I want the final list to be like that :               {{1, 3}, {2, 5}, {3, 6}}.      Here the first element of the sub list is needs to check with other sub list's first element and remove the sub list where first element repeated again. So the final list doesn't have `{2,4}` because `2` is repeated twice.


How to delete duplicated sublist

I have a list like this:               rew={{{2011, 3, 13, 0, 0, 0}, 1044.4}, {{2011, 3, 13, 3, 0, 0}, Missing["NotAvailable"]},      {{2011, 3, 13, 3, 0, 0}, 1044.7}, {{2011, 3, 13, 6, 0, 0}, 1043.4},      {{2011, 3, 13, 9, 0, 0},1041.5}, {{2011, 3, 13, 12, 0, 0}, 1044.1},      {{2011, 3, 13, 15, 0, 0}, 1045.4}, {{2011, 3, 13, 18, 0, 0}, 1046.8},      {{2011, 3, 13, 21, 0, 0}, 1047.5},.....}      How do I delete duplicated sublists? From this list I want to delete                {{2011, 3, 13, 3, 0, 0}, Missing["NotAvailable"]}, {{2011, 3, 13, 3, 0, 0}, 1044.7}      this sublists which have duplicates because the first part is the same. And also delete duplicates if I face the duplicates


Dependency injection - use a specific implementation of one function within another

Consider...               f[x_]:=Body containing h[some args]...     g[x_]:=Body containing h[some args]...      However I want to define something like...               The h to use inside f has this definition h[args___]:=f specific definition.     The h to use inside g has this definition h[args___]:=g specific definition.      I know I can do this using Block wrapped around the call to f and g but I was curious if some cunning extension of UpValues would work; more like a dependency injector pattern. My experience of using UpValues is very limited and reading the documentation for UpValues it would appear to be appropriate only when the precise pattern of h within f or g is known. Added 26/08/2014 10:11 (London) The specific problem I was trying to apply this to concerned two very similar functions that produce some graphics. Those graphics required different scaling functions to produce their results. What I wanted to do was attach in some way the specific scaling to the relevant function but separate from the plotting functions themselves. Block comes closest to what I was trying to achieve. I may go with this. Many thanks to all who answered.


Simulation code performance tuning

The following simulation takes over 20 seconds for evaluation. I have difficulty re-coding it with Nest and Map or Compile functions to make it more efficient. Can some one help with this? **The overview of the code is:** It is a numerical solution for evolution of density of vehicles on a corridor that has `L` lanes. The corridor is split into `n` sections of `dx` length and each section has a sink and source coming from a ramp (which intern is divided into `p` segments each). the network is loaded from on-ramps with density `A` for `m` time periods only and simulated till the network is empty. The variable `a1` is the control of inflow from the ramps on to the corridor. The outflow factor is B. The output of the simulation is the total density observed over the whole simulation. Also, how can I use parallelization on this code?               demand[n_, k_] := Min[k Vf, n capacity];     supply[n_, k_] := Min[(n Kj - k) w, n capacity];     flo[n_, Ku_, Kd_] := Min[demand[n, Ku], supply[n, Kd]];     dx = 1/6; n = 48; m = 300; p = 36; capacity = 2500; A = 18.; B = 0.1; L = 3.;      RML = 30; Vf = 100; Kj = 150; w = 20; dt = 1/600;          f[a1_] :=      Module[{G,k0=ConstantArray[0, n],k, kr=Table[Table[0,{i1,1,p}],{i2,1,n}],P},      k = k0; RM = 100 a1; j = 0; RampSpill = 0;     For[i = 2, i < n, i++, kr[[i, 1]] = A];      NtwrkTT = TT = Plus @@ (Plus @@ kr);     While[TT > 0, TT = 0;      Do[FQin = If[i == 2, Min[demand[L, k0[[i - 1]]], supply[L, k0[[i]]]], FQout];      dem = demand[L, k0[[i]]]; dem = If[dem == 0, 0.001, dem];      G = Min[1, supply[L, k0[[i + 1]]]/dem];      P = G demand[1, kr[[i, p]]];      Qr = (P - B FQin) dx;      FQout = Min[demand[L, k0[[i]]], supply[L, k0[[i + 1]]]];      k[[i]] = k0[[i]] + (FQin - FQout + Qr)/Vf;      kr0 = kr[[i]];      Do[MR = If[ir == RML + 1, RM, capacity];       RQin = Min[MR, If[ir == 2, flo[1, kr0[[ir - 1]], kr0[[ir]]], RQout]];       MR = If[ir == RML, RM, capacity];       RQout =Min[MR, If[ir < p, flo[1, kr0[[ir]], kr0[[ir + 1]]], P]];       kr[[i, ir]] = kr0[[ir]] + (RQin - RQout)/Vf, {ir, 2, p}];      kr[[i, 1]] = If[j <= m, A, 0], {i, 2, n - 1}];     TT = Plus @@ (Plus @@ kr);     TT += Plus @@ k;     k0 = k; NtwrkTT += TT; j++];     NtwrkTT dt] // Timing     f[14]      **Edit:** Please find below the profile output:![enter image description here](http://i.stack.imgur.com/a6Iqy.jpg)


combining manipulate with "static" plot

Is there a way to show a plot of a "static" function as background for a manipulate panel ? In other words: I have put into a manipulate a trajectory (solution of a system of two differential equations):               solcontrol =      FullSimplify[       DSolve[{y'[t] == - y[t] - u z[t],                z'[t] == -1 -2 z[t] + u y[t], y[0] == 0, z[0] == -.5},                {y[t], z[t]}, t]];      Then, I use Manipulate               {{ysol[t_], zsol[t_]}} =        Simplify[{y[t], z[t]} /. solcontrol,        Assumptions -> Element[u, Reals] && t > 0];          With[{y = ysol[t], z = zsol[t]},         Manipulate[         ParametricPlot[{y, z}, {t, 0, tend}],           {{tend, .1}, 0, 20},{{u, .7}, 0, 20}]]      Remark/problem:I'm using Mathematica 9 on a Debian. I don't know if you see the same manipulate panel as me on (say) Windows, but my panel sets its dimension "dynamically" respect on the form of trajectories. Finally, my problem is to show the result of manipulate with this contour plot:               DeltaA[y_, z_] = -y^2 - z -2 z^2;     DeltaB[y_, z_] = -2 y z - y;           ContourPlot[{DeltaA[y, z] == 0, DeltaB[y, z] == 0}, {y, -1,1},{z, -1, 1}]      because I want to see how trajectories behave respect the line of the plot. thank you


Slow mixture fitting when having ill-conditioned covariance matrices. How to make it faster?

I'm using Mathematica 9.0 to fit multidimensional observations with a gaussian mixture. To do so I first adapted these steps to ensure that the mixture parameters are well defined (see http://mathematica.stackexchange.com/a/16833/12672). Runing time was unacceptable (I waited some hours and aborted it afterwards), so I tried the fitting in Matlab. Matlab instantly retrieved an error message from the clustering algorithm that states "ill-conditioned covariance created at iteration 3". To overcome this I tried 2 solutions concerning the covariance matrices definitions following the suggestions in http://stackoverflow.com/a/16263971 and http://www.mathworks.com/matlabcentral/answers/100210. To reproduce my problem and illustrate my experiments here I enclose some data, part of my original data, this being 7 samples each 5-dimensional, which I try to fit in a 2 gaussian mixture:               data = {{0, 2.76, 10.68, 12.4133, 9.26667}, {0, 0, 0, 0, 1.13333}, {6.06667, 8.32, 6.86667, 6.6, 4.49333}, {1.25333, 5.96, 7.49333, 5.81333, 5.05333}, {0, 0, 1.13333, 6.42667, 7.41333}, {0, 0, 0, 3.25333, 3.82667}, {0.76, 6.28, 10.28, 9.05333, 5.12}};     data // MatrixForm     d = Dimensions[data]     nDim = Last[d];     nMixtures = 2;      **One solution** is to **use a single covariance matrix for all the mixtures**. What follows is the implementation in Mathematica:               For[k = 1, k < nMixtures + 1, k++,          m[k] = Table[mm[k, i], {i, nDim}]];(*means*)     For[k = 1, k < nMixtures, k++,          w[k] = Exp[ww[k]]/((1 + Exp[ww[k]])*(nMixtures - 1))]; (*mixture weights*)     c = Table[If[i >= j, cc[i, j], 0], {i, nDim}, {j, nDim}];(*triangular matrix*)     s = c.Transpose[c];(*covariance matrix*)     M = Append[Array[w, nMixtures - 1], 1 - Total[Array[w, nMixtures - 1]]];(*all weights, which sum up to 1*)     Q = {};     For[i = 1, i < nMixtures + 1, i++,          Q = Insert[Q, MultinormalDistribution[m[i], s], i]];(*all mixtures, which share the same covariance matrix*)      The corresponding **fitting takes 85 seconds in my PC** using the following command:               edf_shared = EstimatedDistribution[data, MixtureDistribution[M, Q]]; // Timing      The same implementation **in Matlab takes 0.0047 seconds** :               data = [0,0,6.0667,1.2533,0,0,0.76; 2.76,0,8.32,5.96,0,0,6.28; 10.68,0,6.8667,7.4933,1.1333,0,10.28; 12.4133,0,6.6,5.8133,6.4267,3.2533,9.0533; 9.2667,1.1333,4.4933,5.0533,7.4133,3.8267,5.1200]';     edf_shared = gmdistribution.fit(data,nMixtures,'SharedCov',true);      **Another way** to go around this problem is, instead of using the same covariance matrix for all gaussians, **add a small epsilon to the diagonal of the covariance matrices**. **In Mathematica it takes 29,247 seconds (about 8 hours)** :               For[k = 1, k < nMixtures + 1, k++,          m[k] = Table[mm[k, i], {i, nDim}]];(*means*)     For[k = 1, k < nMixtures, k++,          w[k] = Exp[ww[k]]/((1 + Exp[ww[k]])*(nMixtures - 1))];(*mixture weigths*)     For[k = 1, k < nMixtures + 1, k++,          c[k] = Table[If[i >= j, cc[k, i, j], 0], {i, nDim}, {j, nDim}]];(*triangular matrices*)     epsilon = 0.00005;     epsilonMatrix = DiagonalMatrix[ConstantArray[epsilon, nDim]];(*diagonal matrix*)     For[k = 1, k < nMixtures + 1, k++,          s[k] = c[k].Transpose[c[k]] + epsilonMatrix];(*covariance matrices*)     M= Append[Array[w, nMixtures - 1], 1 - Total[Array[w, nMixtures - 1]]];     Q = {};     For[i = 1, i < nMixtures + 1, i++,          Q = Insert[Q, MultinormalDistribution[m[i], s[i]], i]];(*all mixtures, with regularized covariance matrices*)     edf_epsilon = EstimatedDistribution[data,MixtureDistribution[M, Q]]; // Timing      The corresponding implementation **in Matlab takes 0.0055 seconds** :               edf_epsilon = gmdistribution.fit(data,nMixtures,'Regularize', 1e-5);      Neadless to say, **when evaluating the estimated distribution function on a point, execution time is also an issue**. The implementation using shared covariances in Mathematica requires 276 seconds, while in Matlab is just 0.41 seconds. The first approach involving a shared matrix, when applied to this new point takes 107 seconds in Mathematica and 0.20 seconds in Matlab. **I also tried playing with the _EstimatedDistribution_ function parameters** such as _WorkingPrecision_ , _AccuracyGoal_ , _ParameterEstimator_ , etc., I didn't see any substantial improvement. At most, when I reduced the _WorkingPrecision_ to 5 I managed to cut down the estimation time to just 40 seconds. **My question is whether there is a better way to do this** , I mean to estimate the parameters of a gaussian distribution in Mathematica while coping for ill-conditioned covariance matrices. By better I mean **faster while keeping a relatively good accuracy in the estimations** , in the Matlab direction I enclosed here. Perhaps there is some issue with my code, or the approaches themselves are intrinsically inconvenient in Mathematica. Any suggestion will be welcome, thanks in advance!


Combination of CellPrint and PrintTemporary, or DisplayForm for Cells

I'm programmatically generating some formatted output that generates a cell in the form of a `Cell[]` expression. For instance, the output might be               cell = Cell[TextData[{"Function ",         Cell[BoxData[FormBox[RowBox[{"f","(","x",")"}],             TraditionalForm]], FormatType->"TraditionalForm"]}],        "Subsection"];      (where $f(x)$ will actually be some complicated expression). **How can I get the rendered`Cell` expression displayed in the notebook temporarily during evaluation?** I can display it (permanently) in the notebook using `CellPrint`: ![CellPrint](http://i.stack.imgur.com/nT9Cu.png) I can display text temporarily using `PrintTemporary`: ![PrintTemporary](http://i.stack.imgur.com/pOVpD.png) But combining them doesn't work, because `PrintTemporary` assumes its argument is an expression to print rather than a box structure: ![PrintTemporary doesn't work](http://i.stack.imgur.com/9mqEH.png) Adding `DisplayForm` doesn't work; it seems `DisplayForm` only works for boxes when not wrapped in a complete `Cell` expression: ![DisplayForm doesn't work](http://i.stack.imgur.com/4EBMo.png) So I really need a `CellPrintTemporary` function.


How can I get a Taylor expansion of the Sin[x] function?

How can I get a Taylor expansion of the Sin[x] function by the power series?


Unevaluated symbols

I often find it useful to define a symbol from strings (often in a loop in which I define other symbols). This I accomplish with `Symbol` (and often `ToString`). However, if the symbol has already been defined, my call to `Symbol` returns not the symbol, but that to which the symbol evaluates. This may arise rarely, but I stumbled upon it when automatically generating `usage` messages, as in the following example.               vars = {x,y};     x$dN = {x1, x2};     y$dN = {y1, y2};     For[ i = 1, i <= Length[vars], i++,       Evaluate[         Symbol[           ToString[vars[[i]]] <> "$dN"         ]       ]::usage       =       "generic (no argument) thermodynamic quantity vector"     ]          (* Symbol::symname: The string "{x1, x2}$dN" cannot be used for a symbol name.         A symbol name must start with a letter followed by letters and numbers" *)      This is the obvious error because I'm trying to define the `usage` for `x$dN`, which evaluates to `x$dN = {x1, x2}`. So my question is: can we sometimes leave a symbol unevaluated, yet use it as a symbol?


Cell brackets on left side?

Is it possible to have the cell brackets on the left? I looked through the options and couldn't find anything, but maybe it's some kind of esoteric style setting or something. The reason I'm looking for this is because the content of notebooks is on the left, which means that's where my mouse hangs out most of the time. So I suspect having the cell brackets on the left would be more natural. (I'm aware of the cellgroup openers, my question is about general selecting/manipulating, not just opening/closing).


Is there an NDSolve`ProcessEquations analog for NIntegrate?

NDSolve has an interface for repeatedly solving an equation with different initial conditions without having to analyze the equation and set up the solving algorithm each time. This can improve performance dramatically. For example,               In[1]:= nd = First@NDSolve`ProcessEquations[{y'[t] == -y[t], y[0] == 1}, {y}, t]          Out[1]= NDSolve`StateData[<0.>]           In[2]:= solve[y0_] := Module[{}, nd = First@NDSolve`Reinitialize[nd, y[0] == y0];                             NDSolve`Iterate[nd, 1]; NDSolve`ProcessSolutions[nd]]          In[3]:= Timing[NDSolve[{y'[t] == -y[t], y[0] == #}, {y}, {t, 0, 1}] & /@Range[0.001, 1, 0.001]] // First          Out[3]= 0.527396          In[4]:= Timing[solve /@ Range[0.001, 1, 0.001]] // First          Out[4]= 0.250309      Is there an analogous interface to `NIntegrate` that would allow me to process the integral once, then do integrations using the same integration method (as chosen by `NIntegrate`) repeatedly using different constants in the integrand and/or different limits of integration?


Driven simple harmonic oscillator — amplitude of steady state motion

I am (partly as an exercise to understand _Mathematica_ ) trying to model the response of a damped simple harmonic oscillator to a sinusoidal driving force. I can solve the differential equation with some arbitrarily chosen boundary conditions, and get a nice graph;               params = {ν1 -> 1.0, ω1 -> 10.0, F -> 4.0};     system =        {D[x1[t], {t, 2}] == -ν1 D[x1[t], t] - ω1^2 x1[t] + F Cos[ω t], x1[0] == 1, x1'[0] == 0};     soln = DSolve[system /. params, x1[t], t][[1]][[1]];     Plot[x1[t] /. soln /. ω -> 8, {t, 1, 20}, Frame -> True, Axes -> False]      ![SHM transients](http://i.stack.imgur.com/tRS4H.png) But I don't care about the transients - I just care about the steady state situation. I tried using Limit to extract this;               amp = Table[Max[Limit[x1[t] /. soln, t -> ∞]], {ω, 1, 20, 1}]     ListPlot[amp]      ![response](http://i.stack.imgur.com/df9l9.png) Looks a bit peculiar to me. Also, this is incredibly slow, and doesn't work symbolically. I thought I could do something along the lines of forcing it to take as a solution of the DE $a Sin(\omega t + \phi)$;               params = {ν1 -> 40.0, ω1 -> 10.0, F -> 10.0};     x1 = a Sin[ω t + ϕ];     system = D[x1, {t, 2}] == -ν1 D[x1, t] - ω1^2 x1 + F Cos[ω t]     amp = Solve[system /. params, a]     phase = Solve[D[a /. amp, t] == 0, ϕ][[1]][[1]]      but this just turns into a mess and doesn't give the right result either. Is there a canonical way to tackle this sort of problem? I don't really know what I'm doing with Mathematica yet, so any explanations would be gratefully received.


$RecursionLimit::reclim: Recursion problem

Please, find bellow my original question. Here is all my code:               vm = 5;     r0 = 127.25;     di = r0*2;     de = 273;     v = 0.000000464;     ρf = 958;     ρt = 7854;     pr = 2.88;     kf = 0.656;     kt = 58;     cf = 4186;     ct = 470;     re = (vm*(2*r0/1000)/v)     e = 0.00015;     f = 1.325 (Log[0.27*(e/(2*r0/1000)) + 5.74*(1/re)^0.9])^(-2)     tinf = 298;     tme = 373;     αf = kf/(ρf*cf)     c1 = (-f*ρf*vm^2/(4*r0/1000))     g = 9.81;     β = 1/((tme + tinf)/2)     var = 0.000018;     prar = 0.703;     α = 0.000025;     kar = 0.028;          ym[r_] := (((r0/1000) - r)*vm*(f/8)^(0.5))/v;     εm[r_] := v*(0.4*ym[r]/6)*(1 + (r/(r0/1000)))*(1 + 2*(r/(r0/1000))^2);          momento = NDSolve[{(1/r)*D[(v + εm[r])*r*D[u[r], r], r] == (1/ρf)*c1, u'[0.0000001] == 0, u[(r0/1000)] == 0},u[r], {r, -0.0000001, (r0/1000)}, MaxSteps -> 10000];     mom[r_] = u[r] /. First[momento];          hi = (kf/(2*r0/1000))*((re - 1000)*pr*(f/8))/(1 + 12.7*(f/8)^0.5*(pr^(2/3) - 1))     ra = (g*β*((tme + tinf)/2 - tinf)*(de/1000)^3)/(var*α);     he = (kar/(de/1000))*(0.6 + (0.387*ra^(1/6))/(1 + (0.559/prar)^(9/16))^(8/27))^2      Here starts my problem. Mathematica isn't able to solve systems of PDEs with more than one independent variable. But Mathematica is able to solve each one individually. So, I have to solve iteratively both the two equation varying a boundary condition (by the way, it is a partial elliptic equation). But, at the moment this is not the problem.               l = 200;     tempo = 100;     Clear[tmed];      Clear[tmedpred];      Clear[ttf];      Clear[med];     Clear[tpred];      tmed[x_, t_] := tinf; (*Initial*)     med[x_, t_] := tinf; (*Initial*)     tmedpred[x_, t_] := tinf; (*Initial*)     tpred[x_, t_] := tinf; (*Initial*)     ttf[x_, r_, t_] := tinf; (*Initial*)     subrel = 0.4;     eps = 10^-4;          (*While[erro\[GreaterEqual]eps,*)          enf1 = NDSolve[{(ρf*cf*(D[tf[x, r, t], t] + mom[r]*D[tf[x, r, t], x])) == ((1/r)*        D[(r*(αf + εm[r])*D[tf[x, r, t], r]), r]),tf[x, r, 0] == (tme - tinf)*Exp[-1000*x] + tinf,tf[0, r, t] == tme, (D[tf[x, r, t], r] /. r -> 0.0000001) ==       0, -kf*(D[tf[x, r, t], r] /. r -> (r0/1000)) == (1 - Exp[-1000*x])*hi*(tmed[x, t] - ttf[x, r0/1000, t])},tf[x, r, t], {x, 0, l}, {r, 0.0000001, (r0/1000)}, {t, 0, tempo}, Method -> {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MinPoints" -> 13}}];     tff[x_, r_, t_] = tf[x, r, t] /. First[enf1];          med[x_, t_] := (NIntegrate[(mom[r]*tff[x, r, t]*r), {r, 0.0000001, r0/1000}])*2/((2/((r0/1000)^2)*NIntegrate[(mom[r]*r), {r, 0.0000001, r0/1000}])*(r0/   1000)^2));          tpred[x_, t_] := tmedpred[x, t] + subrel*(med[x, t] - tmedpred[x, t]);     tmed[x_?NumericQ, t_?NumericQ] := tpred[x, t];          ent1 = NDSolve[{ρt*ct*(D[tt[x, r, t], t]) == (1/r)*(D[(r*kt*D[tt[x, r, t], r]), r]), tt[x, r, 0] == tinf, -kt*(D[tt[x, r, t], r] /. r -> (r0/1000)) == (1 - Exp[-1000*x])*hi*(tmed[x, t] - ttf[x, r0/1000, t]), -kt*(D[tt[x, r, t], r] /. r -> (de/2000)) == (1 - Exp[-1000*t])*he*(ttf[x, de/2000, t] - tinf)}, tt[x, r, t], {x, 0, l}, {r, (r0/1000), (de/2000)}, {t, 0, tempo}];          tmedpred = tmed      Here is the problem. "tmedpred" shall return to the structure of the first NDSolve (enf1) and the code keep the loop up to an error value. Realize that the While structure is not in the code. I'm doing a manual evaluation. The error: $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> The box message: "A very large output was generated. Here is a sample of it: (<<1>>) + subrel (med[100, 50] - tmedpred[100, 50]) The problem starts with the input tmedpred = tmed (original question) I have two function:               med[x_?NumericQ,         t_?NumericQ] := ((NIntegrate[(mom[r]*tff[x, r, t]*r), {r,             0,             r0/1000}])*(2/((2/((r0/1000)^2)*               NIntegrate[(mom[r]*r), {r, 0, r0/1000}])*(r0/                1000)^2)));      and,               tmed[x_, t_] := tmedpred[x, t] + subrel*(med[x, t] - tmedpred[x, t]);      `mom[r]` and `tff[x,r,t]` are `NDSolve` output. This functions are inside a While code and at the end of the loop, `tmedpred = tmed` (`tmedpred` become `tmed` and the While code should keep iterating up to an error value) `tmedpred[187,100]` (it is a simple evaluation of the function) At this moment the warning > "$RecursionLimit::reclim: Recursion depth of 1024 exceeded." And a box with the message > "A very large output was generated. Here is a sample of it:" > > (<<1>>) + subrel (med[187, 100] - tmedpred[187, 100])) + subrel (med[187, > 100] - tmedpred[187, 100]) Could some one help me with this problem? I was wondering if it is possible to create a function that is not connected to the original function but keep its original behavior(a kind of numerical function). Regards!


How to make equidistant or split ListPoint

How to split the curve with more equidistant points?                  lpts={{1., 0., 0.}, {0.540302, 0.841471, 0.25}, {-0.416147, 0.909297, 0.5},          {-0.989992, 0.14112, 0.75}, {-0.653644, -0.756802, 1.}, {0.283662, -0.958924, 1.25},            {0.96017, -0.279415, 1.5}, {0.753902, 0.656987, 1.75}, {-0.1455, 0.989358, 2.},          {-0.91113, 0.412118, 2.25}};             l = Line@lpts;        Show[Graphics3D[{Blue, Thick, l}, Boxed -> False],          Graphics3D[{Red, PointSize[Large], Point[lpts]}]]      ![enter image description here](http://i.stack.imgur.com/w6mJt.png)


Generating evenly spaced points on a curve

In the `KnotData` package a simple command such as               points = Table[KnotData[{3, 1}, "SpaceCurve"][t], {t, 0, 2 Pi, 0.1}];      will generate a series of points that comprise a knot (here, a trefoil, if successive points are connected). However, the distance between points is not constant; is there a way to generate evenly spaced points? (I.e. evenly spaced arc lengths between points).


Scaling an image with "Drawing Tools" primitives on it

Imagine I doodle with the "Drawing tools" pen, or place lines on an image after importing it. Now say I want to scale this image by some constant factor $C$ while maintaining the same aspect ratio. How can I correspondingly scale my "Drawing tools" objects?


Back Linear Substitution

I have an equation set `Ax=b` and `A(n*m),n<m` . To lower down the dimension, I express some vars by other vars, which gives `By=c`. After some calculation, the values of `y` is achieved and I want to get `x` back. How can I accomplish this work? **The main aim is to get the substitution and back substitution, instead of solving the equations.** Remark: `n` and `m` are not fixed, the code need to be general for different scales. For example:               x[1]+x[2]+x[3]==1&&x[2]+x[4]==1      Then we have:               x[1]==x[4]-x[3]&&x[2]==1-x[4]      And after some calculation, I get `{x[3],x[4]}=={0,1}` and I want to get:               {x[1],x[2],x[3],x[4]}=={1,0,0,1}      I know it's silly to use `x[i]`, as I can't handle matrices well. I believe there is a way to finish all these in the language of matrices.


How to find integer solutions?

Following is the equation: ![enter image description here](http://i.stack.imgur.com/IKvhW.png) Need to solve for integer values of x,y when a,b lies between -1000 and 1000. Problem is to find the number of integer values of pair (x,y) that satisfy it.


Exporting/Importing a Table of complex numbers

I'm generating a long table of list of the form: `PN={{1,2,1+i},{3.5,2.6,2}...},{...},...` Using: `Export["PN.dat", PN, "Table"]` Seems to do the job of exporting, but then using: `PN = Import["PN.dat", "Table"] or PN = ReadList["PN.dat"]` Can't reconstruct the same List, the first way considers the imaginary number i as something else "I", while the second one returns insane data like: `{{-1., -2.6464*10^-40, 0. + 2.76621*10^18 I}, {-0.129967...` Any ideas how to do this right? (Using ToExpression Returns $Faild)


Tiling a square

I wondered if there was a way to automate the process of finding a way to tile a tile into a square. The idea is to represent the tile with a matrix of $0$s for blank space and $1$s for filled spaces like in $\\{\\{0,1,1\\}, \\{1,0,0\\}\\}$. ![The tile.](http://i.stack.imgur.com/0k8C4.png) The square (or a general rectangular area) is represented by an array as well. The function should then have as arguments two lists (representing the tile and the area) and should find the ways (if they exist) to do the tiling. This is quite an hard problem for me, I have tried playing with `Plus`, so that if the result matrix has $2$ it means that the tile overlaps while if it is $0$ there is a gap but I can't find a way to tell _Mathematica_ that they should fit the area.


Line of best fit on LogLog plot

I have a LogLog plot, and i'm unsure about how to fit a line to it. The data represents a calibration curve.                calibdata = {{1, 39270.4}, {0.01, 4982.57}, {0.001, 1153.55}}      ListLogLogPlot[calibdata, PlotMarkers -> {Automatic, Medium}]


Building a continued fraction

I've completed a problem that involves approximating $e$ by a continued fraction: $$\frac{N_1}{D_1+\frac{N_2}{D_2+\frac{N_3}{\ddots+\frac{N_k}{D_k}}}}$$ with the $N_i$ being the list `{1,1,1, …}` and the $D_i$ being the list `{1,2,1,1,4,1,1,6,1,1,8, …}`. (Note: The continued fraction actually approximates $e-2$). The overarching structure of computing the continued fraction is a straightforward application of `Fold` with the following function defined:               f[x_, {m_, d_}] := m/(d+x);     eContFracApprox[n_] := Fold[f, 0, (*properly constructed list of pairs*)]      which shifts the crux of the problem to generating the lists for $N_i$ and $D_i$ and combining them properly. I have a solution, but I'm not happy with it:               Reverse[     MapThread[       List, {Table[1, {n}],         Take[Flatten[{Join[{1, 2}, Table[{1, 1, i}, {i, 4, n, 2}]]}],n]}     ]     ]      I think it's ugly and it doesn't work for values of $n < 3$. Perhaps someone can suggest a different/better approach? Specifically, I'd like to know if we can do away completely with `MapThread` and generate the list of pairs directly from an application of `Table`. * * * **Edit 1** : Just to be clear. I'm looking for an improvement to generating the lists of the $N_i$ and $D_i$. Although, alternate ways of generating continued fractions are also appreciated. I'll also add my complete function for reference:               eContinuedFractionApprox[n_Integer] := Module[{f},       f[x_, {m_, d_}] := m/(d + x);     N[Fold[f, 0,      Reverse[       MapThread[List,        {Table[1, {n}], Take[Flatten[{Join[{1, 2}, Table[{1, 1, i},              {i, 4, n, 2}]]}],          n]         }        ]       ]      ],     n     ] + 2      ]


Check when DSolve returns input

I'm making a program where i need to plot the soluton of an ODE and ,if possible, obtain the analytical solution. My idea was to use DSolve, check the output, and if it failed use NDsolve. Now, i know i can set a time limit using `TimeConstrained[]` , but how do i check when DSolve instantly return the input because the alculation is too complex or there is no analytical solution? sorry if this was answered elsewere, i tried to search but i couldn't find anything related.


Changing Plot order for 3D printing

Alright, I got a my first 3D print done of a pseudosphere using parametric plot and a deflated sphere using a contour plot, but when I try               ParametricPlot3D[         {Cos[v]*(3 - u) + .25*Sin[4 u],           Sin[v]*(3 - u) + .25 Sin[4 u],           u},        {u, 6, 13}, {v, 6, 13},       PlotStyle -> {Thickness[.3], FaceForm[Yellow, Blue]},        PlotPoints -> {50, 50}, MaxRecursion -> 0, Mesh -> All]       it gives an error about triangulation self-intersects. I do not have the exact error code because I'm not in charge of the MakerBot. It makes the first round and then stops. I noticed that the estimated time was 50 times longer than it took for that first loop. Is there a way to fix that, and maybe a changing plotting order would be more machine friendly?


Finding connected components in an array

I have an $w\times h$ array with non-negative integers. I wish to partition the set of coordinates $(c,r)$ with $1\leq c \leq w$ and $1\leq r \leq h$, in subsets, so that each subset corresponds to a cluster of the same value in the array. Two coordinates are neighbouring if they either are on top of another, or one is down-left of the other. This corresponds to finding clusters in a parallelogram. belisarius was nice to provide a picture: ![enter image description here](http://i.stack.imgur.com/kJEhK.png) I have some code to find one connected cluster in an array (I call it gt):               FloodFillExtractTile[gt_, {sr_, sc_}] :=       Module[{r, c, toExplore, visited = {}},       toExplore = {{sr, sc}};       While[Length@toExplore > 0,        (* Pop *)        {r, c} = Last@toExplore;        toExplore = Most[toExplore];        AppendTo[visited, {r, c}];        (* Down-left *)             If[c > 1 && r < h &&           gt[[r + 1, c - 1]] == gt[[r, c]] && !            MemberQ[visited, {r + 1, c - 1}],         AppendTo[toExplore, {r + 1, c - 1}];         ];        (* Down-right *)             If[ r < h &&           gt[[r + 1, c]] == gt[[r, c]] && ! MemberQ[visited, {r + 1, c}],         AppendTo[toExplore, {r + 1, c}];         ];        (* Up-right *)             If[r > 1 && c < w &&           gt[[r - 1, c + 1]] == gt[[r, c]] && !            MemberQ[visited, {r - 1, c + 1}],         AppendTo[toExplore, {r - 1, c + 1}];         ];        (* Up-left *)             If[ r > 1 &&           gt[[r - 1, c]] == gt[[r, c]] && ! MemberQ[visited, {r - 1, c}],         AppendTo[toExplore, {r - 1, c}];         ];        ];       Return@visited;     ];      Then `FloodFillExtractTile[gtp, {1, 1}]` gives the component connected to the upper left hand corner. However, this method feels ugly, and extending it to all components feels even uglier. I was looking at `Gather`, but the problem is that it wants _all_ points in a cluster to be _equal_ , see for example Gather dependency on list order? Edit: So this is the type of arrays I am looking at. The 6, the 3's, the 2's and the 0's are in one component respectively, but there are two components with 1's. Being neighbours means being adjacent down-left, down-right, up-left and up-right. Now, the rows is stored just like regular rows in a rectangular matrix, so that is why this translates to a bit strange criteria for being neighbours. ![GT-pattern](http://i.stack.imgur.com/LrdCQ.png) This is the best code I have so far, first extract points with the same value, then do connected-component analysis on those parts.               GetGTTiles[gtp_] :=        Module[{testSame, testEdge, h, w, pts, sameClusters, getEdges,          tiles},        {h, w} = Dimensions[gtp];        pts = Join @@ Table[{r, c}, {r, h}, {c, w}];        testSame[{r1_, c1_}, {r2_, c2_}] := (gtp[[r1, c1]] ==            gtp[[r2, c2]]);        testEdge[{r1_, c1_}, {r2_,            c2_}] := (gtp[[r1, c1]] ==             gtp[[r2, c2]]) &&          ((c1 == c2 &&               Abs[r1 - r2] <= 1) || (c1 == c2 - 1 &&               r1 == r2 + 1) || (c1 == c2 + 1 && r1 == r2 - 1));        sameClusters = Gather[pts, testSame];        getEdges[clust_] :=          Join @@ Outer[If[testEdge[#1, #2], #1 -> #2, Sequence @@ {}] &,            clust, clust, 1];        tiles =          Join @@ (ConnectedComponents[Graph@getEdges[#]] & /@ sameClusters);        Return@tiles;        ];      This is the output I expect for the example given (5 clusters found):               {{{1, 1}}, {{1, 2}, {2, 1}},      {{1, 3}, {2, 3}, {3, 2}, {4, 1}, {3, 1}, {2, 2}},      {{1, 4}},      {{2, 4}, {3, 4}, {4, 4}, {5, 4}, {5, 3}, {4,3}},      {{3, 3}, {4, 2}, {5, 2}, {5, 1}}}      EDIT: So this is the final code, based on belisarius solution:               GTTiles[gtp_List] := Module[{fromEuclidean, toEuclidean,         getOneTile, elements, elmPos, pts, tile, tiles},             (* This is used to changefrom different coordinate systems. *)             fromEuclidean[{r_, c_}] := {r, (c - r)/2 + 1};        toEuclidean[{r_, c_}] := {r, 2 c + r - 2};             getOneTile[pts_List, maxDist_?NumericQ] := Module[{f},          f = Nearest[pts];          FixedPoint[           Union@Flatten[f[#, {Infinity, maxDist}] & /@ #, 1] &, {First@             pts}]];             elements = Union @@ gtp;        elmPos = (toEuclidean /@ Position[gtp, #]) & /@ elements;        (* This is really strange code. *)        tiles = Flatten[Flatten[             Reap[NestWhile[Complement[#,                  Sow@getOneTile[#, N@Sqrt@2]] &, #, # != {} &]][[2]],              1] & /@ elmPos, 1];        tiles = Map[fromEuclidean, tiles, {2}];        Return@tiles;        ];


Variable scoping in Module

I don't understand why $a$ and $b$ are not local in the following code:               Clear[lint];     lint[f_, x_] := Module[{a, b}, f /. Replace[x, {a_, b_} -> a -> b]];          Clear[a];     lint[x, {x, t}] (* returns t, as I would expect *)          a = 3;     lint[x, {x, t}] (* returns x *)          Clear[a]; a=3;     lint1[f_, x_] := Module[{a, b}, f /. Replace[x, {a_, b_} :> a -> b]]; (* returns t *)      It appears that the occurrence of $a$ in the pattern inside the replace is being interpreted in the outer scope. Why is that? Update: Having read @szabolcs comment and the first answer, I still don't quite understand. First, the documentation for `Rule` says that "Symbols that occur as pattern names in lhs are treated as local to the rule.". Fine, that's what the comment said. But if they are local, then why is $3$ substituted for $a$ in the second example above? Second, why does using `:>` solve the problem? The only difference between `Rule` and `RuleDelayed`, as far as I can see, is when the _right-hand_ symbols are evaluated. So why does this change the behavior? (See the new fourth example above).


Is it possible to find a function from first few terms in the expansion

Is it possible to find a function if first few terms of the expansion is known. For example if I have this series $f(x)=\frac{k^3 x^2}{6}-\frac{k^5 x^4}{120}+\frac{k^7 x^6}{5040}-\frac{k^9 x^8}{362880}+\frac{k^{11} x^{10}}{39916800}+\cdots$, is it possible to find what would be the full function? (answer: $k- \sin(kx)/x$). One suggestion I find for a problem close to this is to use `GeneratingFunction`, but for that It is necessary to know the form the $n^\text{th}$ term in terms of the exponent of different variable which is often quite difficult. What I am looking for is an algorithm which can guess a possible form of the full function if first few terms are given.


NDSolve for PDE with discontinuous initial/terminal condition

I have an issue with NDSolve for the case of a PDE with discontinuous initial/terminal condition. Consider the PDE solution               Z=z/.First[NDSolve[{       D[z[t,x],t] == z[t,x] D[z[t,x],x]-1/2 (1-t)^2 D[z[t,x],{x,2}],       z[1,x]==UnitStep[x],       z[t,-5000]==0,       z[t,5000]==1},       {z},{t,0,1},{x,-5000,5000}]]      The terminal condition is the discontinuous UnitStep function. When I plot the solution for t=1 now,               Plot[Z[1, x], {x, -10, 10}]      ![plot](http://i.stack.imgur.com/5d344.png) Mathematica has obviously smoothened the terminal condition (which was explicitly given by the UnitStep function). Is it possible to disable this smoothing? Or at least, I want to have a smooth function that does not exceed 1 and does not go below 0. Note: What I am not searching for is a solution like "increase the MaxSteps" or something similar. I am interested in options on how Mathematica processes the initial/terminal condition. Thanks a lot for your help!!


Caesar's cipher

How can Caesar cipher be implemented? I want to use `StringReplace` but I don't know how to write the replacement rule to replace the characters with, say, the character two positions down in the alphabet.


Trying to access Twitter returns Cannot import data as JSON

I am trying to use the Social features of Mathematica 10. The Facebook interaction works, but with Twitter I am getting "Cannot import data as JSON". Example:               In[16]:= ServiceExecute["Twitter", "LastTweet", {"ScreenName" ->         "stephen_wolfram"}]          During evaluation of In[16]:= Import::fmterr: Cannot import data as JSON format. >>          Out[16]= ServiceExecute["Twitter", "LastTweet", {"ScreenName" ->         "stephen_wolfram"}]      I have tried `ClearSystemCache[]` but this has no impact. I am getting the valid token from Twitter and it is marked as an allowed App with read access. If I use `SocialMediaData[]` it fails but returns numbers. Example:               In[17]:= SocialMediaData["Twitter", "Followers"] // Short      Generates this: ![output showing numbers](http://i.stack.imgur.com/IplUx.png) Can anyone tell me what I am doing wrong, or how to diagnose/solve this? **[Edit]** Further testing. Restarting the client then `ServiceExecute[]` works. However `SocialMediaData[]` doesn't. Restarting the client and running `SocialMediaData[]` first fails but displays some names. Eg. ![enter image description here](http://i.stack.imgur.com/q5IZz.png) Also I've noticed that ServiceExecute allows you to save your Auth key, but SocialMediaData doesn't.


Cannot plot Quantity values with DateListPlot

Is there a way to use `DateListPlot` with `Quantity` values? I retrieved the following time series data from WolframAlpha:               gasPrices = WolframAlpha[     "us gas prices", {{"History:Price:GasPriceData", 1},      "TimeSeriesData"}];      Each data point is composed of a date and a `Quantity`:               {{{1993, 4, 5, 0, 0, 0.}, Quantity[1.068, ("USDollars")/("Gallons")]},      {{1993, 4, 19, 0, 0, 0.}, Quantity[1.079, ("USDollars")/("Gallons")]},     ...      {{2012, 12, 31, 0, 0, 0.}, Quantity[3.369, ("USDollars")/("Gallons")]} }      I can plot the values using `ListPlot`:                ListPlot[gasPrices[[All,2]]]      ![enter image description here](http://i.stack.imgur.com/uy8vH.png) Strangely however, `DateListPlot` produces an empty plot:                DateListPlot[gasPrices]      ![Empty plot from DateListPlot](http://i.stack.imgur.com/3Kstn.png) To get `DateListPlot` to produce a proper plot I have to do this instead:               DateListPlot[ Transpose[{gasPrices[[All, 1]], gasPrices[[All, 2, 1]]}] ]      ![OK plot from DateListPlot](http://i.stack.imgur.com/EXfGf.png) Am I missing something? I would have thought that `Quantity` values could be taken directly by `DateListPlot`, as they are by `ListPlot`.


Horizontal shift in fitting data by a sinusoidal nonlinear model

I have data that can apparently be fitted by a sinusoidal function in form $D+A\sin(B(x-\frac CB))$. I tried doing the best fit in _Mathematica_ using `NonlinearModelFit` function. I got a message saying it failed to converge with current accuracy and max iterations, so I tinkered a little bit with the function, but it made a model far from being the best fit for the data. I tried replacing parameters with constants and it turned out the problem was in finding $B$, or the horizontal shift, since I got a satisfactory fit when I specified the shift. So my question is: Is there a work-around for this problem, so I can find the best horizontal shift? **Note:** I tried it with the form $D+A\sin(Bx-C)$ with the same problem. **Edit:** This is the requested data, note that in the second `NonlinearModelFit`, I specified `b` and it worked like a charm:               data = {{10, 716}, {20, 727}, {30, 744}, {40, 762}, {50, 783},{60, 804},             {70, 826}, {80, 848}, {90, 872}, {100, 894}, {110, 915}, {120, 935},             {130, 954}, {140, 969}, {150, 982}, {160, 990}, {170, 993},              {180, 992}, {190, 986}, {200, 975}, {210, 961}, {220, 944},             {230, 926}, {240, 905}, {250, 883}, {260, 861}, {270, 839},             {280, 817}, {290, 795}, {300, 774}, {310, 755}, {320, 738},             {330, 723}, {340, 712}, {350, 706}, {360, 706}}          NonlinearModelFit[data, d + a Sin[b (x - c)], {a, b, c, d}, x]["BestFit"]      > During evaluation of NonlinearModelFit::cvmit: Failed to converge to the > requested accuracy or precision within 100 iterations. >   >   >     853.439 - 1717.86 Sin[0.94244 (10.0078 + x)] >                 NonlinearModelFit[data, d + a Sin[b (x - c)] /. b -> π/185, {a, c, d}, x]["BestFit"]      > >     849.276 + 141.098 Sin[π/185 (-1930.24 + x)] >


Programming a recursive FFT with Mathematica

I'm trying to program a FFT using a recursive function in _Mathematica_ , though my program is not getting me anywhere at the moment. Could you say what's wrong with it and what I can do to make it work? My program is the following: (We assume that a is a list of size $2^s$ for some integer $s$)                FFT[a_] :=            (n := Length[a];       If[n == 1, Return[a],       f := Exp[2 I Pi/n];       o := 1;       b := Drop[a, {1, Length[a], 2}];       c := Drop[a, {2, Length[a], 2}];       d := FFT[b];       e := FFT[c];       For[k = 0, k < n/2, k++,       y[k] := d[[{k}]] + o e[[{k}]];       y[k + n/2] := d[[{k}]] - o e[[{k}]];       o = o f]       Return[Table[y[i], {i, 1, n}]]])


Intersection of two splines

I have a collection of sets of points, each set defining the segment of a (nice) curve on the unit sphere $S^2 \subset \mathbb{R}^3$. The points are computed numerically. I now want to compute the intersection of the curve segments and I would like to get all solutions if two curve segments intersect more than once. The following Mathematica script works but only gives me one solution:               f1 = BSplineFunction[points[[1]]];     f2 = BSplineFunction[points[[2]]];     g[u_, v_] := Norm[f1[u] - f2[v]]     NMinimize[{g[x, y], 0 <= x <= 1, 0 <= y <= 1}, {x, y}]      Using               NSolve[g[x, y] == 0, {x, y}]      simply yields the function call as an output, and               FindRoot[g[x, y] == 0, {{x, 0.5, 0, 1}, {y, 0.5, 0, 1}}]      complains that the number of variables does not match the number of equations. Any suggestions on how to solve this? Edit2: This is a sample of the data I am using that I would like to yield two points of intersection               points =     {{{ 0.0563319, -0.0207277,  -0.998197}, { 0.0468164,  -0.020208,  -0.998699},        { 0.0361213, -0.0187319,  -0.999172}, { 0.0269836,  -0.0165999, -0.999498},        { 0.0191223, -0.0140227,  -0.999719}, { 0.0122367,  -0.0111131, -0.999863},        { 0.00603102,-0.00789628, -0.999951}, { 0.000232715,-0.00432551,-0.999991},        {-0.00539442,-0.000299408,-0.999985}, {-0.0110431,   0.00431947,-0.99993},        {-0.0168598,  0.00968684, -0.999811}, {-0.0229461,   0.0159607, -0.999609},        {-0.0293624,  0.0232877,  -0.999298}, {-0.036133,    0.031792,  -0.998841},        {-0.0432526,  0.0415674,  -0.998199}, {-0.0506922,   0.0526714, -0.997324}},       {{-0.0563319,  0.0207277,  -0.998197}, {-0.0468164,   0.020208,  -0.998699},        {-0.0361213,  0.0187319,  -0.999172}, {-0.0269836,   0.0165999, -0.999498},        {-0.0191223,  0.0140227,  -0.999719}, {-0.0122367,   0.0111131, -0.999863},        {-0.00603102, 0.00789628, -0.999951}, {-0.000232715, 0.00432551,-0.999991},        { 0.00539442, 0.000299408,-0.999985}, { 0.0110431,  -0.00431947,-0.99993},       { 0.0168598, -0.00968684, -0.999811}, { 0.0229461,  -0.0159607, -0.999609},        { 0.0293624, -0.0232877,  -0.999298}, { 0.036133,   -0.031792,  -0.998841},        { 0.0432526, -0.0415674,  -0.998199}, { 0.0506922,  -0.0526714, -0.997324}}};


Finding the intersection of a curve with an interpolation function

There are no issues trying to find the intersection points of two defined curves.                   f[x_] := 2 (x - 1) (x - 1.5) (x - .5) (x + .5) (x + 1) (x + 1.5);         g[x_] := 0.4 x - 0.4;         Solve[f[x] == g[x], x]         (*{{x -> -1.39849}, {x -> -1.20949}, {x -> -0.331841}, {x ->            0.426865}, {x -> 1.}, {x -> 1.51295}}*)         Manipulate[Plot[Evaluate[{f[x], g[x]}], {x, -1.5, 1.52},                     Epilog -> {Red, PointSize[Large],                     Point[{#, f[#]} & /@ (x /.                     Solve[f[x] == g[x], x])]}], {a, -0.8, .5, .2}]      ![enter image description here](http://i.stack.imgur.com/HUdTQ.png) When I try to perform the same but this time with an interpolation function I run into problems.               points = Table[{x, f[x]}, {x, -1.5, 1.5, .25}];     if = Interpolation[points];      I can obtain the first intersection by using the following. Neither NSolve nor Solve will work with interpolation function. With Solve this will happen               Solve[if[x] == g[x], x]      Solve::inex: Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system. Since many of the methods used by Solve require exact input, providing Solve with an exact version of the system may help. >> With NSolve, you get a similar error.               NSolve[if[x] == g[x], x, Reals]      ( _NSolve[InterpolatingFunction[{{-1.5,1.5}}, <>][x]==-0.4+0.4 x,x,Reals]_)               FindRoot[if[x] == g[x], {x, -1.5}]     (*{x -> -1.36794}*)      Which makes this question different from marking points of intersections between two curves as the problem is specific when using InterpolationFunction What is the best way to find all intersection points between the range (-1.5 and 1.5)?


How to Invert a Multivariate Interpolating Function?

I used NSolve on a partial differential equation with boundary conditions to get a numerical solution that Mathematica says is of the form InterpolatingFunction. I then defined a function f(x,y) which evaluates this solution for a given (x,y). I want to be able to retrieve all of the values of (x,y) such that f(x,y) = C for a given constant C, and then pick the (x,y) in this set that maximizes a different (non-interpolative) function g(x,y). Is this possible? If so, how?


How I can use Apply or Map with If?

I have list of objects:                list = {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}, {13, 13, 0.05, 0.05}};           list = {{x,y,Vx,Vy},{x,y,Vx,Vy},...};      And               object = {10, 10};      I want when I change position of object the objects from the list to follow the first object. I try with this:               If[object[[1]] < #1 && #3 > 0, list = {#1,#2,-#3 ,#4}, list = {#1,#2,#3,#4}] &@@@list     If[object[[1]] > #1 && #3 < 0, list = {#1,#2,-#3 ,#4}, list = {#1,#2,#3,#4}] &@@@list     If[object[[2]] < #1 && #4 > 0, list = {#1,#2,#3 ,-#4}, list = {#1,#2,#3,#4}] &@@@list     If[object[[2]] < #1 && #4 < 0, list = {#1,#2,#3 ,-#4}, list = {#1,#2,#3,#4}] &@@@list      and works but only the first cycle. I know that I can do this with:               If[object[[1]] < list[[1, 1]] && list[[1, 3]] > 0, list[[1, 3]] *= -1]....      But is very slow and not look nice :). And doesn't work completely correct.


Plot electric potential and field

I am trying to plot an electric pottentional of a dielectric cylinder along with it's field. The pottentional is a piecewise function               F[r_, f_] :=       Piecewise[{{-2 e r Cos[f]/(1 + er),      0 <= r < a}, {-e r Cos[f] + (er - 1)*a^2 *e*r^(-1)*Cos[f],      r >= a}}](*electorstatic pottential*)     e = 500;(*outer electric field*)     a = 0.02;(*cylinder's radius*)     er = 2;(*relevant acceptance*)      What's the best way to plot this function(pottential), with it's derivative(electric field)? I tried to plot it using `ContourPLot` but it doesn't look nice(I am not a Mathematica expert apparently)               ContourPlot[-2 e r Cos[f]/(1 + er), {r, 0, a}, {f, 0, 2 Pi}]     ContourPlot[-e r Cos[f] + (er - 1)*a^2 *e*r^(-1)*Cos[f], {r, a,      2 a}, {f, 0, 2 Pi}]     Show[%, %%]      ![](http://i.imgur.com/FkJkt.png) What I am trying to achive is a sophisticated plot,with the cylinder at the origin, where the equipottential lines and the electric field lines will be plotted. I found something like that on the net (specifically the page "Gradient field plots in Mathematica"), but I don't know how to modify it...               gradientFieldPlot[f_, rx_, ry_, opts : OptionsPattern[]] :=       Module[{img, cont, densityOptions, contourOptions, frameOptions,         gradField, field, plotRangeRule, rangeCoords},        densityOptions =         Join[FilterRules[{opts},           FilterRules[Options[DensityPlot],            Except[{Prolog, Epilog, FrameTicks, PlotLabel, ImagePadding,              GridLines, Mesh, AspectRatio, PlotRangePadding, Frame,              Axes}]]], {PlotRangePadding -> None, Frame -> None,           Axes -> None, AspectRatio -> Automatic}];       contourOptions =         Join[FilterRules[{opts},           FilterRules[Options[ContourPlot],            Except[{Prolog, Epilog, FrameTicks, PlotLabel, Background,              ContourShading, PlotRangePadding, Frame, Axes,              ExclusionsStyle}]]], {PlotRangePadding -> None, Frame -> None,           Axes -> None, ContourShading -> False}];       gradField = ComplexExpand[{D[f, rx[[1]]], D[f, ry[[1]]]}];       field =         DensityPlot[Norm[gradField], rx, ry,          Evaluate@Apply[Sequence, densityOptions]];       img = Rasterize[field, "Image"];       plotRangeRule = FilterRules[Quiet@AbsoluteOptions[field], PlotRange];       cont = If[         MemberQ[{0,            None}, (Contours /. FilterRules[{opts}, Contours])], {},          ContourPlot[f, rx, ry, Evaluate@Apply[Sequence, contourOptions]]];       frameOptions =         Join[FilterRules[{opts},           FilterRules[Options[Graphics],            Except[{PlotRangeClipping, PlotRange}]]], {plotRangeRule,           Frame -> True, PlotRangeClipping -> True}];       rangeCoords = Transpose[PlotRange /. plotRangeRule];       Apply[Show[          Graphics[{Inset[             Show[SetAlphaChannel[img,                "ShadingOpacity" /. {opts} /. {"ShadingOpacity" -> 1}],               AspectRatio -> Full], rangeCoords[[1]], {0, 0},              rangeCoords[[2]] - rangeCoords[[1]]]}], cont,           StreamPlot[gradField, rx, ry,            Evaluate@FilterRules[{opts}, StreamStyle],            Evaluate@FilterRules[{opts}, StreamColorFunction],            Evaluate@FilterRules[{opts}, StreamColorFunctionScaling],            Evaluate@FilterRules[{opts}, StreamPoints],            Evaluate@FilterRules[{opts}, StreamScale]], ##] &,         frameOptions]]      This can be run like that               gradientFieldPlot[(y^2 + (x - 2)^2)^(-1/         2) - (y^2 + (x - 1/2)^2)^(-1/2)/2, {x, -1.5, 2.5}, {y, -1.5,        1.5}, PlotPoints -> 50, ColorFunction -> "BlueGreenYellow",       Contours -> 10, ContourStyle -> White, Frame -> True,       FrameLabel -> {"x", "y"}, ClippingStyle -> Automatic, Axes -> True,       StreamStyle -> Orange]      And the amazing output is ![](http://i.imgur.com/qlDMM.png) What I would like to do is ![](http://i.imgur.com/1JVe9.jpg)


Can you call a C function that takes function pointers as arguments?

I want to use MathLink to call a function I wrote in C. However, similar to an integrator, it takes a function pointer as an argument and applies it on numbers depending on the other arguments. I know how to pass lists of reals and so on, but can you also pass pointers to functions defined in Mathematica? In the end, it should look something like this:               f[x_,y_] := x*y; Install["mycprogram"]; MyCFunction[f,1,2]      `f` is a function that takes two doubles and returns a double. It's fairly simple and should always be some combination of polynomials, fractions, `Log` and `Exp`.


Visualize cluster distances in DendrogramPlot

I want to perform a cluster analysis using the `HierarchicalClustering` package. Is there a way to display the inter-cluster distances in a dendrogram plot? An example how the result should look like: ![here](http://i.stack.imgur.com/DsPJT.jpg).


Initializing Minimization

I am trying to implement a model predictive control scheme in _Mathematica_ , e.g. I optimize input sequences by predicting future outputs. So every time I call the cost function it will simulate the system and produce the desired function value. Since the cost function has to call `NDSolve`, there is no symbolic representation and trying to call the cost with symbolic variables will not produce any results. Now, whenever I try to minimize my cost function, _Mathematica_ tries to evaluate the cost function symbolically:               FindMinimum[J[As, bs, cs, x0s, predY, Table[u[i], {i, 10}], 49, g, .1], Table[{u[i], 0}, {i, 10}]]     (* NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`. >>        ReplaceAll::reps: {NDSolve[{(x[1]')[t]==0. +1. x[2][t],(x[2]')[t]==0. +1. x[3][t],(x[3]')[t]==0. +u[1]-7.90817 x[2][t]-7.5181 x[3][t],x[1][0]==6.29161,x[2][0]==7.04417,x[3][0]==6.94553},{x[1],x[2],x[3]},{t,0,0.1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >> *)      and a couple of more like that telling me that _Mathematica_ doesn't know what to do with nonnumerical values. How can I force _Mathematica_ to initialize the minimization numerically, without trying to find some gradient symbolically?


How do I get the critical value in statistical hypothesis testing?

What I am trying to do is to get the value of $\chi^2$ for given probability (let us say $\alpha$=0.01) and degrees of freedom (for example df=3). How do I get that? Inverse...Distribution functions return something quite different from expected. Thanks in advance.


Question about sum and list in a function

I have a list of this form: $ lst =\left\\{\left\\{q_1,x_1,y_1,z_1\right\\},\left\\{q_2,x_2,y_2,z_2\right\\},\text{...},\left\\{q_n,x_n,y_n,z_n\right\\}\right\\} $ I want to use this list in the function: $V(\\{x,y,z\\})=\sum _{i=1}^n \frac{q_i}{\sqrt{\left(x_i-x\right){}^2+\left(y_i-y\right){}^2+\left(z_i-z\right){}^2}}$ Where n is the lenght of the list n = Length[lst]. I am not sure how i get this into a inpute code. I have tried the following with the list lst and function v2 :               lst= {{1, 0, 0, 0}, {1, -1, 0, 0}, {1, 1, 0, 0}};       $ \text{V2}(\\{\text{x$\\_$},\text{y$\\_$},\text{z$\\_$}\\},\text{lst$\\_$})\text{:=}\sum _{i=1}^n \frac{\text{lst}[[\text{All},1]]}{\sqrt{\left(\text{lst}[[\text{All},2]]_i-x\right){}^2+\left(\text{lst}[[\text{All},3]]_i-y\right){}^2+\left(\text{lst}[[\text{All},4]]_i-z\right){}^2}}$                   V2[{x_, y_, z_}, lst_] :=             Sum[lst[[All,1]]/Sqrt[(Subscript[lst[[All,2]], i] - x)^2 + (Subscript[lst[[All,3]], i] - y)^2 +                 (Subscript[lst[[All,4]], i]- z)^2], {i, 1, n}];       * * *                   Apply[V2, {{x, y, z}, lst}]      Gives : $ \left.\frac{1}{\sqrt{\left(\\{0,-1,1\\}_2-x\right){}^2+\left(\\{0,0,0\\}_2-y\right){}^2+\left(\\{0,0,0\\}_2-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_3-x\right){}^2+\left(\\{0,0,0\\}_3-y\right){}^2+\left(\\{0,0,0\\}_3-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_1-x\right){}^2+\left(\\{0,0,0\\}_1-y\right){}^2+\left(\\{0,0,0\\}_1-z\right){}^2}},\frac{1}{\sqrt{\left(\\{0,-1,1\\}_2-x\right){}^2+\left(\\{0,0,0\\}_2-y\right){}^2+\left(\\{0,0,0\\}_2-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_3-x\right){}^2+\left(\\{0,0,0\\}_3-y\right){}^2+\left(\\{0,0,0\\}_3-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_1-x\right){}^2+\left(\\{0,0,0\\}_1-y\right){}^2+\left(\\{0,0,0\\}_1-z\right){}^2}},\frac{1}{\sqrt{\left(\\{0,-1,1\\}_2-x\right){}^2+\left(\\{0,0,0\\}_2-y\right){}^2+\left(\\{0,0,0\\}_2-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_3-x\right){}^2+\left(\\{0,0,0\\}_3-y\right){}^2+\left(\\{0,0,0\\}_3-z\right){}^2}}+\frac{1}{\sqrt{\left(\\{0,-1,1\\}_1-x\right){}^2+\left(\\{0,0,0\\}_1-y\right){}^2+\left(\\{0,0,0\\}_1-z\right){}^2}}\right\\}$ But i am expecting to get $\frac{1}{\sqrt{x^2+y^2+z^2}}+\frac{1}{\sqrt{(x+1)^2+y^2+z^2}}+\frac{1}{\sqrt{(x-1)^2+y^2+z^2}} $ What am i doing wrong?


Why didn't Reduce give me the right result?

My code:               Clear[r1, r2];      par[r1_, r2_] := r1 r2 / (r1 + r2);      Reduce[{5 par[r2, 32000]/(r1 + par[r2, 32000]) == 1.8 && par[r1, r2] == 5000}, {r1, r2}]      with this result: ![enter image description here](http://i.stack.imgur.com/xGpr3.png) I checked it a dozen times, but I can't see why MMA doesn't give me a value for r1. So, like I always do when I'm desperate :-), I quit and restarted MMA. Copied and pasted my input. And ecco!: ![enter image description here](http://i.stack.imgur.com/g5go4.png) Any idea what could have caused the first result?


Probability of the sum of the largest n samples

15 numbers are randomly chosen from U(0,1), what is the probability that the sum of largest four numbers is greater than 3.5?                   With[{f = OrderDistribution[{UniformDistribution[], 15}, #] &},           Probability[a + b + c + d > 3 + 1 / 2,           {a \[Distributed] f[15], b \[Distributed] f[14], c \[Distributed] f[13],           d\[Distributed] f[12]}]]      Trouble is, it is very, very slow. I shut it down after 30 minutes. When I used NProbability it converged on the wrong answer but it did warn me with numerous error messages. Another CAS could do the above code but it also returned the same wrong answer. The right answer is supposed to be (it at least agrees with a simulation): $\frac{224077804910008595}{584325558976905216} $ $\approx 0.383481094515780$ How do I do this using Mathematica?


First evaluation fails

I am fairly new to _Mathematica_ (version 7), so please bear with me... I have duplicated, in _Mathematica_ , a program that I originally wrote in C (it generates OEIS sequence A191837). The problem is that each time I make a change to the function `nCk` the first evaluation doesn't print. I have to stop the evaluation and then start it again to see the result of my change. What am I missing? Also, does anyone have any tips on how to make the code more compact?               For[smnds = 4; m = 6, smnds <= 60, m += 6,       s = {};       sum = smndct = pct = 0;       For[p = 5, p < m/2, p += 2,        If[PrimeQ[p] && PrimeQ[m - p],         If[sum + p > m, Break[]];         If[smndct++ < smnds - 1, sum += p];         AppendTo[s, p];         pct++]];       If[pct >= smnds, sdf = Range[smnds];        While[nCk[Length[s], smnds]]]       ];     (* Subsets[] uses too much memory, so process each         combination one at a time. *)      nCk[vy_, vz_] :=       Block[{indx = ns = vy, i = rs = vz, ct = tot = 0},        If[(sdf[[1]] - 1) == (ns - rs),         For[ct = 1, ct <= rs, ct++, tot += s[[sdf[[ct]]]]];         If[tot == m, Print["a(", smnds/2, ") = ", tot];          smnds += 2; m -= 6; Return[False], Return[False]]];        While[sdf[[i]] == indx && i > 1, --i; --indx];        sdf[[i]] += 1;        i++;        While[i <= rs, sdf[[i]] = sdf[[i - 1]] + 1; ++i;];        For[ct = 1, ct <= rs, ct++, tot += s[[sdf[[ct]]]];         If[tot > m, Break[]]];        If[tot == m, Print["a(", smnds/2, ") = ", tot];         smnds += 2; m -= 6; Return[False]];        Return[True]        ];


Undocumented Dynamic Function question

In the code below the value displayed next to the slider may be correct, and should be the result of The value of `x` for `cyL` and the value of `x` for change at the slider position. Slider position 0 should provide the first values for `x` in these lines. Now if I evaluate `x`outside of the function after moving the sliders, it only returns the slider position and not the value of `x` from the function. How can I get the variable to return the correct value for each slider? Thanks!               cyL[x_] :=        58.770000000000046` - 3.557000000000158` x -         3.525333333333144` x^2 + 4.987999999999908` x^3 -         1.3386666666666487` x^4;          cyA[y_] := -35.13365403304179` - 0.009572400388682331` y +         0.08989310009715228` y^2 - 0.01687074829931251` y^3;          change[x_] := -0.17006802721089645` + 62.92517006802724` x -         6.802721088435384` x^2;          Column[{{Slider[Dynamic[x, Automatic]],         Dynamic[cyL[change[x]]]}, {Slider[Dynamic[g, Automatic]],         Dynamic[cyA[change[g]]]}}]