Transformation rule on a list of non-negative integers

I am trying to create a transformation rule that takes a list of non-negative integer values of any length, finds a non-zero entry in the list, adds 1 to all preceding numbers, subtracts 1 from the chosen non-zero entry, and keeps the subsequent values untouched. As an example, `{0,1,0,2,3,0}` could be transformed into `{1,0,0,2,3,0}`, `{1,2,1,1,3,0}` or `{1,2,1,3,2,0}`. I'm looking for a transformation rule, let's call it say `desiredrule`, such that `ReplaceList[{0, 1, 0, 2, 3, 0}, desiredrule]` yields those three lists above. My (failed) attempt at this was along these lines:               ReplaceList[{0, 1, 0, 2, 3, 0}, {x___, y_ /; y > 0, z___} -> {x + 1, y - 1, z}]      which results in:               {{1, 0, 0, 2, 3, 0}, {2, 1, 3, 0}, {4, 2, 0}}      The key issue is obviously the `x + 1` but I'm not sure how to correct this. I know of other ways to achieve this same result without using `ReplaceList`; I know I could, for example, do the following:               transform[list_] :=       Module[{nonzeropositions, numberoftransformations},        nonzeropositions = Flatten@Position[list, x_ /; x > 0];        numberoftransformations = Length[nonzeropositions];        Table[list[[i]] + If[i < nonzeropositions[[j]], 1, 0] +          If[i == nonzeropositions[[j]], -1, 0], {j,          numberoftransformations}, {i, Length[list]}]]      But I'm specifically interested to learn how I could achieve this result via the transformation rule approach I outlined initially.


FindSelectedFunction for packages - how to make it work?

The _Mathematica_ help menu contains an entry _Find Selected Function_ (`Cmd`+`Shift`+`F` on OSX). If you are working with say `Transpose` and want to look up its _reference page_ , you just select `Transpose` with the mouse, hit `Cmd`+`Shift`+`F` and _Mathematica_ opens the _reference page_ for `Transpose`. Works beautifully. **Question:** How to get this to work for your own packages? So, suppose your package is correctly built, and it has its own functions:               MySuperFunc     FunkyMonkey     FunkMeister2      and the documentation pages are correctly created, correctly defined and correctly installed for each of those functions. You select `MySuperFunc` with the mouse, select _Find Selected Function_ , expecting _Mathematica_ to open the _reference page_ for that function but it doesn't work. Instead, _Mathematica_ opens up something akin to a Google search on "MySuperFunc", providing a list to anything it can find on that name. But that's not what I want. And it's also not what that menu function is supposed to be doing: Find SELECTED Function! Not a google-type search. Just open the _reference page_ for the selected Function. Anyone have some tips on how to make this work as advertised? * * * Addendum: If one enters:                ?MySuperFunc      ... you get the usual Help blurb on the function, such as:               MySuperFunc[b] returns blah given b. >>      ... and if you then click on those two little `>>` arrows, _Mathematica_ opens the Help _Reference_ page for `MySuperFunc` PERFECTLY, which is exactly what FindSelectedFunction _should_ be doing, but is not doing. And if it works perfectly for the `>>` info blurb, why can't it work just as perfectly for FindSelectedFunction?


How can I name "a[[i]]" the parts of Table "a"? Or how to make Table "a" grow inside FindMinimum?

Let's say I want to minimize a function that uses a `Table` named `a` with the Conjugate Gradient Method of `FindMinimum`. _Instinctively_ I do the following :               FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 2}])^2, {a, {0, 0}}, Method -> "ConjugateGradient"]      But I obviously get the following messages and results : > During evaluation of In[135]:= Part::partd: Part specification a[[1]] is > longer than depth of object. >>   >  During evaluation of In[135]:= Part::partd: Part specification a[[2]] is > longer than depth of object. >> > > {0., {a -> {0., 0.}}} So, to overcome this _little_ difficulty, I tried the following :               a = {a1, a2};     FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 2}])^2, {a, {0, 0}}, Method -> "ConjugateGradient"]      > During evaluation of In[136]:= Part::partd: Part specification a[[1]] is > longer than depth of object. >>   >  During evaluation of In[136]:= Part::partd: Part specification a[[2]] is > longer than depth of object. >> > > {0., {{a1, a2} -> {0., 0.}}} and again I obtain the same error messages. So I came down to the _dirty_ manner:               FindMinimum[(a1*Cos[1.3] + a2*Cos[1.3])^2, {{a1, 2}, {a2, 0}},        Method -> "ConjugateGradient"]      which this time provided me with actual results :               {2.86222*10^-17, {a1 -> 1., a2 -> -1.}}      Now, while this last alternative works for this simple example and for a Table containing only two values, It will become impossible if I had to do for example:               FindMinimum[(Sum[a[[i]]*Cos[1.3], {i, 1, 1000}])^2, {a, {0, 0}},        Method -> "ConjugateGradient"]      How can I sort this out? I'm aware that there might something wrong with my approach, but I can't find another manner to set this up.


Animate a position change along the curve for every iteration

I've only had few previous experiences on Mathematica before. So basically an entry-level question that harasses a rookie like me. I made the following attempt using bisection method to calculate the real root for the function $f(x)=-x^3+2x^2-2$ with basic while loop and if: ` a = -5; b = 5; m = (a + b)/2; While [ Abs[f[m]] > 0.000001, If[f[m]*f[a] < 0, b = m, a = m]; m = (a + b)/2]` The answer turns out to be $-(14080895/16777216)$ that is correct. Then, I wanted to create a animation that shows the change of position of a dot along the function curve for each iteration of the bisection method. But I tried several times with different codes that all fails to do so. One confusion is I am not sure how to set up a stepsize here which involves not a constant number but "While" and "If". Would you please help me animate the iteration with while and if?


Creating a version of SequenceAlignment that accepts patterns

`SequenceAlignment` seems like a function that is not (yet?) fully integrated into Mathematica. I want a function that accepts general patterns instead. I naively fed a `StringPattern` instead of a literal string to `SequenceAlignment` and met silence, though `MatchQ` is positive:               {StringMatchQ["A", Alternatives["A", "B"]], SequenceAlignment["A", Alternatives["A", "B"]]}     (* Out= {True, SequenceAlignment["A", "A" | "B"]} *)      One approach would be to write out all alternatives and repeatedly feed them to `SequenceAlignment`. The question is strongly related to this one: How to generally match, unify and merge patterns?. **Background:** I want to answer questions like _"What DNA sequences give rise to a given protein sequence and where can you find them?"._ Then one naturally stumbles across `Alternatives`. For example, a transmembrane protein that is supposed to selectively filter K ions contains an amino acid sequence "TVGYG". I want to find all its DNA parents, ie DNA code of all proteins that may contain such a filter. Due to the redundancy of the genetic code, that subsequence can be coded by a diversity of DNA sequences, giving rise to a `StringExpression` with alternatives:               In[80]:= StringReplace["TVGYG", backlist]         Out[80]= "ACA" | "ACC" | "ACG" | "ACT" ~~ "GTA" | "GTC" | "GTG" | "GTT" ~~       "GGA" | "GGC" | "GGG" | "GGT" ~~ "TAC" | "TAT" ~~       "GGA" | "GGC" | "GGG" | "GGT"      The first residue, `"T"` for Threonine, may thus be coded by either `"ACA"` or `"ACC"` or `"ACG"` or `"ACT"`, etc.


ListPlot style and axes

I have this list saved in matrix 6x2: \begin{array}{cc} 0 & 1.216 \\ \frac{\pi }{3} & 0 \\ \frac{2 \pi }{3} & 0.1351 \\ \pi & 0 \\ \frac{4 \pi }{3} & 0.04863 \\ \frac{5 \pi }{3} & 0 \\ \end{array} Now i have saved this matrix in a variable called myList: { { 0 , 1.215 } , { π/3 , 0 } , { (2π)/3, 0.1351 } , { π , 0 } , { (4π)/3 , 0.04863 } , { (5π)/3 , 0 } }    if i use the comand:               ListPlot[myList, AxesLabel -> {\[Omega], Subscript[C, n]},       Filling -> Axis]<br>      the result is this:   ![enter image description here](http://i.stack.imgur.com/No8nt.png) The problem 1 is:   i would like to see the blue points and the line under them with RED color.      The problem 2 is:   I don't see the first coordinate on the plot `{0,1.1215}`   there is a way to set the range of y for example (from 0 to 2) and of x for example (from0 to 5) ??? in this way i can see all points.      The problem 3 is:   i would like to see the $\omega$ axe with the Trigonometric value instead of the natural number.   thanks


Using a List in PlotLabel which goes beyond width of ImageSize

My `PlotLabel` goes beyond the width of the `ImageSize`. The label is generated into a `List` form by my program. I hope to allow my `PlotLabel` to go to a second, third, fourth (...) line if it reaches beyond the boundaries. My problem in simplified, working code:               testList = {1.1`, 1.2100000000000002`, 1.4641000000000004`,         2.143588810000001`, 4.594972986357221`, 21.1137767453526`,         445.7915684525922`, 198730.12250342217`, 3.949366159022518`*^10,         1.5597493058032278`*^21, 2.432817896953651`*^42,         5.918602919737985`*^84, 3.5029860521531003`*^169,         1.22709112815791634686748164742131068419446205954341`15.\     653559774527023*^339,         1.50575263680386788043945221511499961813146`15.352529778863042*^\     678, 2.2672910032418008565810795918131168775255956636`15.\     051499783199061*^1356,         5.1406084933812118223464178513329285`14.75046978753508*^2712,         2.64258556822230525123173280428744040060801405497404`14.\     449439791871098*^5425,         6.98325848537680392124060228920952089211156`14.148409796207117*^\     10850, 4.8765899073587133585511396520327915438254972718`13.\     847379800543136*^21701};     Plot[x^2, {x, -3, 3},       PlotLabel -> StringForm["The orbit of x=1.1 is\n``\n", testList ],       ImageSize -> {600, 600}]      ![enter image description here](http://i.stack.imgur.com/uXs1k.png)


Understanding output of multivariable integration

I'm new to Mathematica and I'm trying to integrate this function:               K = Function[{x,theta},       ((b - x^3 (d/(Cos[theta])^2 - b/x)^3) (e - 2 b/x)^3/(((b - x^3 (e - 2 b/x)^3)       (d/(Cos[theta])^2 - b/x)^3))) Sin[theta]]       from $\theta = 0$ to $\theta = \pi$ and from $x = c$ to $x = \frac{f \cos^2(\theta)}{a + \cos^2(\theta)}$ by executing this command:               Integrate[K, {theta, 0, Pi}, {x, c, f((Cos[theta])^2)/(a + (Cos[theta])^2)}].      However, when I do this, the output is $\pi \left(-\left(\left(\sqrt{\frac{a}{a+1}}-1\right) f+c\right)\right) Function\left(\{x,\text{theta}\},\frac{\sin (\text{theta}) \left(\left(e-\frac{2 b}{x}\right)^3 \left(b-x^3 \left(\frac{d}{\cos ^2(\text{theta})}-\frac{b}{x}\right)^3\right)\right)}{\left(b-x^3 \left(e-\frac{2 b}{x}\right)^3\right) \left(\frac{d}{\cos ^2(\text{theta})}-\frac{b}{x}\right)^3}\right)$ What is the meaning of the `Function` part of this result? The result seems like it's a product of the constants and the function itself, but this doesn't make sense because I clearly specified integration limits.


Is there a way to stop evaluation immediately?

Sometimes I'll have a loop that I accidentally made too big. I'll evaluate, and MM will try to run through the entire loop. The program itself doesn't actually seem frozen... I can go to Evaluation-> Abort/Interrupt evaluation, but they don't do anything. I can even save while it's doing this! What seems to kind of work is saving, closing the file, and then going to Evaluation->Quit kernel. But that's a little ridiculous. Is there really no 'hard kill'? Thank you!


Optimization problem test suites

_Mathematica_ provides nonlinear, unconstrained test problems here:               Needs["Optimization`UnconstrainedProblems`"]      and LP test problems here:               ExampleData["LinearProgramming"]      Does anyone know a good source of constrained nonlinear problems in _Mathematica_ format? Also nice to have, but not essential, would be mixed integer linear and nonlinear test problems.


Parametric plot of multiple graphs on the same axes

I'm trying to plot on a single axes system multiple graphs but ran into a problem when tryinf to label my graphs. Here's what I've used so far Mathematica code:               r1 = 0.5;     r2 = 1;     r3 = 2;     r4 = 2.5;     z[r_, t_] = {r ^2 Cos[2 t] - 2 r Sin[t], 2 r Cos[t] + r^2 Sin[2 t]};     zz[t_] = Table[z[r, t], {r, 0.1, 4, 0.5}];     ParametricPlot[{z[r1, t], z[r2, t], z[r3, t], z[r4, t]}, {t, 0,        2 \[Pi]}, PlotRange -> Full, PlotStyle -> {Thick},       AxesLabel -> {"Re(z)", "Im(z)"},       LabelStyle -> Directive[Bold, Large]]      Now, I can't seem to get the legends show, I simply want a number next to each color, say, 0.5 - (green) etc.. Ideally I would like a more elegant solution than having to manually set r1,r2,... Thanks!


Arrow pointing upwards in a Graphics3D

I am trying to write a code for an arrow that points upwards from the center of the circle in a `Graphics3D`.               Manipulate[     Plot3D[RandomReal[{-0.5, 0.5}]*     UnitStep[(x - a)^2 + (y - b)^2 - 1.5^2], {x, -3, 3}, {y, -3, 3},      PlotRange -> All], {a, -1, 1}, {b, -1, 1}]      ![](http://i.stack.imgur.com/1kQfU.png) I want an arrow to point perpendicular from the center of this circle, how can I do that ?


Finding integral points on a surface

Suppose I have a dimension formula (for a Lie algebra representation) that is as follows: $$ d(a,b) = {(a+1)(b+1)(a+b+2) \over 2} $$ Now consider the surface $F(a,b,n) = 0 = d(a,b) -n$ where $n \in \Bbb N$. Is there a Mathematica function that would allow me to find triples $(a,b,n) \in \Bbb N^3$ on this surface?


Mapping the imaginary axis of the complex (s) plane

In this problem is very difficult to analyze the roots s. Firstly I thought that the problem is in precision, but I am not sure. The criterion which I want to obtain is that one of these roots has a positive real part. Characteristic equation has the following form: $$\frac{2 \pi }{\int_{-\infty }^{\infty } \frac{1}{\text{D1}(k,s)} \, dk}+\text{a6} s^2+\text{k0}=0$$ The imaginary axis of the complex s-plane can be parametrized by conidering s=i*r (i=sqrt(-1)). So the equation has new form for consideration                 k0 = a6 r^2 - (1/(2 Pi)       NIntegrate[1/(       a1 a3 k^4 - a2 a4 (-k a5 + r)^2), {k, -\[Infinity], \[Infinity]}])^-1      where               a1 = 2*10^11;     a2 = 7.687*10^-3;     a3 = 3.055*10^-5;     a4 = 7849;     a5 = 500;     a6 = 70;     \[Alpha] = Sqrt[(a1 a3)/(a4 a2)];     c = Sqrt[k0/a6];          a5 > < Sqrt[4 \[Alpha] c];      The mapping rule follows from the characteristic equation, which should be rewritten to express the chosen parameter explicitly. Once the mapping is accomplished, a mapped line is obtained, which divides the parameter plane into domains with different number of roots s* possessing a positive real part. Every line is normally shaded from the side, which is related to the right-hand side of the imaginary axis of the (s)-plane now. Obviously, crossing a decomposition curve in the direction of the shading, one extra root with a positive real part is gained. This curve (rule) should be obtained for parameter r from -Infinity to +Infinity for discuss. So I need two separately diagrams for a5 > Sqrt[4 [Alpha] c] or a5 < Sqrt[4 [Alpha] c]. I am completely not sure how to obtain curves from the equation                 k0 = a6 r^2 - (1/(2 Pi)       NIntegrate[1/(       a1 a3 k^4 - a2 a4 (-k a5 + r)^2), {k, -\[Infinity], \[Infinity]}])^-1      presented here ![enter image description here](http://i.stack.imgur.com/urHhH.jpg) where N is number of roots in the region


How to match a cyclically repeating sequence?

I have run across several times recently where I must match a sequence that is cyclically repeating. For example, with the sequence,               Sequence[a, b, c]      how would I write a pattern that matched against               a     a, b     a, b, c     a, b, c, a      etc., but not any of the surrounding elements? For a two element sequence comprising the entire list, this is straightforward, if a bit verbose:               MatchQ[#, {a | PatternSequence[a, b] .., a | PatternSequence[]}] & /@       {{a}, {a, b}, {a, b, a}, {a, b, a, b, a, b, a}}     (* {True, True, True, True} *)      But, this does not work when the sequence is part of a bigger list, e.g.               Cases[      {q, r, a, b, a, b, a, s, e, f, a},       x : PatternSequence[a|(PatternSequence[a, b] ..), a | PatternSequence[]] :> {x},       Infinity     ]     (* {{a}, {a}, {a}, {a}} *)      Even reversing the initial element to `(PatternSequence[a, b] ..)|a` returns the same thing. So, my questions are:   1. How can I write the pattern so it extracts parts of larger lists that may contain other elements?   2. How can I generalize the pattern to match against larger cyclically repeating sequences?


Mapping multiple functions

This question was part of a course on Mathematica written in 1998. > Each of the functions f1, f2, and f3 defined below has a root near x=2. Map > an anonymous function involving FindRoot[] onto the list {f1,f2,f3} to find > all three roots.                f1[x_]= 2x-17Cos[x]         f2[x_]= x^2-3Sin[x]         f3[x_]= 2Sin[x]^2-x         Plot[{f1[x],f2[x],f3[x]},{x,0,5}]      Which produced the output: > Out[242]= 2 x - 17 Cos[x] > > Out[243]= x^2 - 3 Sin[x] > > Out[244]= -x + 2 Sin[x]^2 ![enter image description here](http://i.stack.imgur.com/9GhD2.png) And then proceeds to draw a nice graph, showing that all of these functions have a root between @1.5 and 1.8. I then individually evaluated the roots (near two) for each function so that I would know if the answers to the "mapped" functions were correct. FindRoot[f1, {2}] > Out[287]= {1.40477}               FindRoot[f2, {2}]      > Out[284]= {1.72213}                FindRoot[f3, {2}]      > Out[285]= {1.84908} Here are some of my attempts to answer the question using `Map` and `FindRoot` along with the error messages and output that each produced. (* Note that I attempted about half a dozen other solutions, but did not want to make this post too long*)                Map[FindRoot, {f1, f2, f3}, {1}]      > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[296]:= General::stop: Further output of > FindRoot::argmu will be suppressed during this calculation. >> > > Out[296]= {FindRoot[f1], FindRoot[f2], FindRoot[f3]}                    Map[FindRoot, {[f1, {2}], [f2, {2}], [f3, {2}]}]      > During evaluation of In[303]:= Syntax::sntxf: "{" cannot be followed by > "[f1,{2}],[f2,{2}],[f3,{2}]}". > > During evaluation of In[303]:= Syntax::tsntxi: "[f1,{2}]" is incomplete; > more input is needed. > > During evaluation of In[303]:= Syntax::sntxi: Incomplete expression; more > input is needed .                    Map[FindRoot, {{f1, {2}}, {f2, {2}}, {f3, {2}}}]      > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= FindRoot::argmu: FindRoot called with 1 > argument; 2 or more arguments are expected. >> > > During evaluation of In[303]:= General::stop: Further output of > FindRoot::argmu will be suppressed during this calculation. >> > > Out[303]= {FindRoot[{f1, {2}}], FindRoot[{f2, {2}}], FindRoot[{f3, {2}}]} I have read the documentation on `Map`, `FindRoot`, `Listable`, `Fold` and `Function`. None of these gave me an idea of how to answer this question. In addition I ran a search of this site(and also looked at each of the threads that were linked when I filled in the subject), the "comp.soft- sys.math.mathematica" site, as well as a general Internet search for "Mapping multiple functions in Mathematica", and didn't find anything that gave me an idea of how to answer the question. I would appreciate someone pointing me in the right direction.


Differential operator squared

I defined a one-dimensional momentum operator $\hat{p}=-i\hbar\frac{\partial}{\partial{x}}$ in Mathematica               p = -I * h * D[#, x]&      and I want to get the kinetic energy operator $\hat{T}=\hat{p}^2/2m=-\frac{\hbar^2}{2m}\frac{\partial^2}{\partial x^2}$ from it, so               T = p^2/(2m)      but it gives the wrong result What can I do about it? Do I have to derive the operators by hand?


Wrapping a function in count

I am working through the _Programming Paradigms via Mathematica (A First Course)_ and am attempting to answer the following: > Use recursion to count how many times the argument can have its square root > taken before the result is less than 2: "manySqrt[x_Real]" should report how > many times the "Sqrt[]" function has to be applied to "x" before the result > is less than 2. For instance, Sqrt[81.0] is 9.0, Sqrt[9.0] is 3.0 and > Sqrt[3.0] is less than 2 so, "manySqrt[81.0]" is 3. Of course, don't use a > logarithm. Additionally: > First, use of a repetition function ("Map[]", "MapThread[]", "Nest[]", > "NestList[]", "Fold[]", "FoldList[]", "Table[]", "Apply[]", and so on, being > our "adverbs") will generally disqualify a method as purely recursive, for > the repetition is accomplished externally from the nested function calls. > Also, repetition accomplished with a loop structure, such as a "While[]", a > "Do[]", or some other repetition command, is explicitly forbidden. My strategy is to make a list of 'Real' values and then count the 'Real' values in the list. I can get the following to work:               Clear[manySqrt]     manySqrt[x_Real] := If[x >= 2, Flatten[Append[{x}, manySqrt[Sqrt[x]]]]]           manySqrt[81.]          (* {81., 9., 3., Null} *)           Count[%, _Real]          (* 3 *)      However I get an erroneous answer when I try to wrap `Count` as follows:               Clear[manySqrt]     manySqrt[x_Real] :=       If[x >= 2, Count[Flatten[Append[{x}, manySqrt[Sqrt[x]]]], _Real]]           manySqrt[81.]           (* 1 *)      I would appreciate a point in the right direction.


Every second evaluation in notebook front end is slow

I'm having a rather baffling problem that Wolfram was unable to help me diagnose, and I'm hoping one of you geniuses in residence here can figure it out. (I don't get access to the Technical Support folks at Wolfram because of the fact that mine is a home license.) If I open a new notebook and run `Factorial[10]//AbsoluteTiming` I will get the expected results for my machine: `{0.000024, 3 628 800}`. However, if I execute it again, the notebook reports "Running" for 3-5 minutes before giving nearly the same output. During that period, the Mathkernel process is cranking with 100% CPU usage, however the actual time reported in the output to perform the evaluation is tiny. There is a pattern. After either canceling the hanging evaluation or letting it run through to its tardy completion, the next evaluation runs normally (i.e. quickly). However, the next evaluation AFTER that hangs again. And the pattern continues indefinitely as far as I have tested it: every other evaluation hangs for 3-5 minutes. My setup: 2012 Macbook Pro Retina running OS X 10.8.3, with Mathematica version 9.0.1.0. I have 8 GB RAM, and plenty of space on my 250GB SSD. 2.3 GHz Intel Core i7. What I have tried: Sleep --> Wake, Restart, Shut Down and Reboot, uninstalling and reinstalling Mathematica, including deactivating and reactivating it. What might be causing this mysterious problem? All other software on the machine is performing normally and I ran the Apple Hardware Diagnostics, which turned up nothing. _UPDATE_ More clues: -Invoking Mathkernel from the terminal to execute an m file works fine. (I haven't tested keeping a Mathkernel alive from the terminal and sending commands one at a time, like you might in the front end.) -If I leave Mathematica and do something else for a few minutes and come back, the first evaluation always works fine and the second hangs. -If I press command+'.' (abort evaluation) before evaluating, it always works. What the....? -If I run Factorial[10]//Timing a few times successfully, the typical response is actually `{6.x10-6, 3 628 800}`


Elliptic curve cryptography in Mathematica

I can find no resources for doing elliptic curve cryptography. I have used the finite field package, but I find it cumbersome and it does not seem to have any builtin methods for ECC. How can I get started doing ECC in _Mathematica_?


Correct use of Mathlink's MLGetRealList

I am attempting to use Mathlink from C. I have managed to return single values from mathlink to my c program, but I am having trouble with lists. Consider the Mathematica operation:               NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}]      This gives us:               {{x -> -0.438447, y -> 1.56155}, {x -> -4.56155, y -> -2.56155}}      Say I wanted to return to my C program a list containing only the second solution i.e. I want {-4.56155,-2.56155}}. I could do this                List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]],       NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]]]      In mathematica, this gives me:               {-4.56155, -2.56155}      All very well, but I worried mathematica is doing Nsolve twice. When I try to replicate this through C like this:               MLPutFunction(link, "EvaluatePacket", 1);         MLPutFunction(link, "ToExpression", 1);         MLPutString(link, (const char *)"List[NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[2]][[2]], NSolve[{x^2 + 4 x + y == 0, y == x + 2}, {x, y}][[2]][[1]][[2]]]");         MLEndPacket(link);              while (MLNextPacket(link) != RETURNPKT)         {              MLNewPacket(link);         }              double *list;         long length;              MLGetRealList(link, &list, &length);              std::cout<<list[0]<<std::cout;              MLDisownRealList(link, list, length);      EDIT: The program sort of completes, but I thin kit is crashing at the end. Now when I print out list[0] and list[1] I get the right answer followed by a hex value. E.g.:               -4.561550x7fff7986fb68      1) How can I return a list of numbers in an elegant fashion through Mathlink? 2) Why is it crashing? Thanks


Redefining built in input aliases

Which file would you need to modify to change the built in definition of the alias [escape] dt [escape] to include parentheses after the partial derivative operator?


Point style in ListPointPlot3D

In `ListPointPlot3D`, it seems the only point style available is the default, because there is no `PlotMarkers` option for this function. Is there a way to change the point style? For example, what if I want to draw the points as small cubes?


Quoting definition explicitly

I'm trying to quote a definition using `DownValues`, `OwnValues`, etc. Everything seems to be fine, except for temporary symbols' annoying appearance in recursive definitions: compare               In[1]:= With[{g = f}, {HoldPattern@g@x_ :> 2 + x}]     Out[1]= {HoldPattern[f[x_]] :> 2 + x}      and               In[2]:= With[{g = f}, {HoldPattern@g@x_ :> 2 + g@x}]     Out[2]= {HoldPattern[f[x$_]] :> 2 + f[x$]}      Here is my version of quoting a definition:               In[3]:= SetAttributes[InheritDefinition, HoldAll];          InheritDefinition[f_Symbol, g_Symbol, rules_:{}] :=     { ClearAll@f     (*, InheritOptions[f, g]*)     , (#@f = With[{g = f}, Evaluate[#@g /. rules]])& /@       {DownValues, OwnValues, SubValues, UpValues}     , FullDefinition@f } // Last      I don't see any need for temporary symbols here at all, since `RuleDelayed` is `HoldRest`, and `HoldPattern` is `HoldAll`. So, `x$` is a dependency that seems totally unnecessary.               In[4]:= ClearAll /@ HoldComplete[oldF, newF] // ReleaseHold;          In[5]:= oldF@x_ := 2 - oldF[2 + x]          In[6]:= newF = "Will be overwritten";          In[7]:= InheritDefinition[newF, oldF]     Out[7]= newF[x$_] := 2 - newF[2 + x$]                  Attributes[x$] = {Temporary}      1) How to quote definitions without temporary symbols? 2) Why exactly is there a difference between `In[1]` and `In[2]`? Is it really because of recursion?


Why is this code in functional style is slower than procedural style?

I know that in Mathematica a functional programming style is often more efficient than procedural style programming using `For` loops. But the code shown below seems to be an exception, How to explain this?               del[ls_, k_] := Delete[ls, List /@ Range[k, Length@ls, k]]          max = 10^5;     r1 = Range[max];     For[i = 2, i <= Length[r1], i++, r1 = del[r1, i]]; // Timing          r2 = Range[max];     Do[r2 = del[r2, i], {i, 2, Length@r2}]; // Timing          r3 = Fold[del, Range[max], Range[2, max]]; // Timing          r1 == r2 == r3      Out:               {0.031200, Null}          {0.889206, Null}          {0.577204, Null}          True


Importing colors from file

I just tried something straightforward (for me):               dummy = Import["http://pastebin.com/raw.php?i=g8D7NprC", "List"] & /@ col;     colors = dummy[[1]];     ToExpression@colors;     Graphics[{colors, Rectangle[{0, 0}]}]      Is it not possible to import color data from a file?


Steady states and eigenvalues for a non-linear system:

I am trying to understand a non-linear system of equations, and find their steady states and dynamics. I am noob to understanding _Mathematica_ (I am using version 6, but I have access to the latest versions in the lab), and I wondered if some kind soul would be able to help me with some of the code. The system is below:               Clear[PBC];     PBC = {       d'[t] == (1/z) (α - β (d[t]/Y[t]) - γ L[t] - δ ψ[t]  - τ Y[t]) + ε (d[t]/ Y[t]) d[t],       L'[t] == (j (Y[t]/f) - e)/N,       ψ'[t] == p L[t] - \[Xi],       Y[t] == (v + b + α - β ( d[t]/Y[t]) - γ L[t] - δ ψ[t])          (ψ[t] + (1 - s) (1 - ψ[t]) - m z)/(1 - (1 - τ))     }     Clear[PBCSS];      PBCSS = Solve[PBC[[1 ;; 3]] /. {g_'[t] -> 0, g_[t] -> g}, {d, L, ψ}] // Simplify     Clear[PBCEigenSystem];     PBCEigenSystem = D[Transpose[PBCSS][[2, 1 ;; 3]], {{d, L, ψ}}] // Simplify) // MatrixForm      I know that I have done some no-no's (already edited in the code above I think), but the code seems to work. However, I am getting some problems with the output. For one, it does not solve all the system. I included some parameters for a numerical solution, but even if you take away the parametrization, it gives the same error as it does not solve for all variables (I have more choppy code to get some solutions for a large n number of iterations, I do not get it for steady states). Furthermore, I seem to be getting an error when I try to get the eigenvalues of the matrix. Also I have been trying to put a Manipulate handle on the steady states and eigenvalue estimation to see where the bifurcations are but I get errors. Any help will be most appreciated!


Using the LQGRegulator to build a human operator model

I'm trying to build a human operator model using an optimal control model in Mathematica: ![Human operator model](http://i.stack.imgur.com/OonUR.png) The vehicle dynamics are given by               a = {{-2, 0}, {1, 0}};     b = {{0}, {1}};     c = {{0, 1}, {1, 0}};     d = {{0}, {1}};      with noise and cost weightings               w = {{4}};     v = {{0.0025}};     q = {{0, 0}, {0, 1}};     r = {{1}};      I generated the state space model and added the time delay ($T_d = 0.2s$) using               ssm = StateSpaceModel[{a, b, c, d}]     td = TransferFunctionModel[SystemsModelDelay[.2]];     ssmWithDelay = SystemsModelSeriesConnect[td, ssm];      Now I am trying model the Kalman estimator and gains ($-l^*$) using a LQG regulator               k = LQGRegulator[{ssm, 1, 1}, {w, v}, {q, r}] // StateSpaceModel      which results in the error               The number of columns in {{},{}} is not equal to the length of {{4}}      I think my problem must be with the noise and cost weightings, but I'm not sure where I went wrong?


Integrating a list of functions

For the purpose of this minimal example, let's say we have a list of functions, like this:               f[y_?NumericQ] := {NIntegrate[z*y, {z, 0, 1}], a y}      I want to integrate an expression involving `f`, say               NDSolve[{y'[t] == f[y[t]][[1]], y[0] == 1}, y[t], {t, 0, 5}]      Now, the problem is that this doesn't return the expected result, because `f[y[t]][[1]]` evaluates to `y[t]` inside the `NDSolve`. How can this be done correctly?


Using an ellipse as a threshold for Nearest function

The `Nearest` function can receive as a threshold parameter a radius to look for elements inside that. From the documentation: > >     Nearest[data,x,{n,r}] give up to the n nearest elements to x within a > radius r >   What about if instead of a circle I want to use an ellipse as a threshold? So I would have an X and Y limit for the `Nearest` function. I know that `Nearest` can receive a `DistanceFunction` as a parameter but I can't think of how to use that for this purpose. Any ideas?


Number theory: Problem involving rational numbers

Use `RandomRat` to test whether `((-1)^(1/Denominator[q]))^Numerator[q]` is identical with `(-1)^q`. Use `25000` rational numbers between `1` and `500000`. Use `Delta =10^-10` and `Map` it to a large list of random rational numbers. If you always get `True` you have evidence for the identity. Then, show that               ((-1)^Numerator[q])^(1/Denominator[q])==(-1)^q      is not an identity. * * * So far this is what I have:               RandomRat := ((-1)^(1/Denominator[q]))^(Numerator[q])     (-1)^q == RandomRat      I'm not sure if that's correct so far because I think I'd have to use pure functions and then how would I use the `25000` rational numbers between `1` and `500000` from here?


How can I randomly color Graphics3D objects?

I have a set of Graphics3D primitives (here, spheres) which I would like to assign either: (1) One of a subset of colors, e.g. {Green, Red} (2) A random color over some RGB interval Writing something like:               Graphics3D[{RGBColor[RandomInteger[{0, 1}], RandomInteger[{0, 1}], RandomInteger[{0, 1}]],Sphere[{#[[1]], #[[2]], #[[3]]}, #[[4]]] & /@ SphereList...      Appears to only assign one random color to all of the spheres. I can force this to work by generating a string that explicitly specifies a random color for each sphere, but is there a simple way to make this work?


Why won't Mathematica work with quantities or Quantity[]?

As you can see in the screenshot below, Mathematica is simply not evaluating any quantities. It is simply listing them as I wrote them. Could anybody give me a pointer as to why this may be? ![enter image description here](http://i.stack.imgur.com/KbG0S.png)


How does parallelization of LibraryLink function call work?

I'm trying to call a C function in parallel through LibraryLink. Here is an example kind of demonstrates that library function can be used in parallel. My question is what happened in the library function call? Does each kernel have its own copy of the library function? Are there some pitfalls we need to watch out when using library functions in parallel?               Needs["CCompilerDriver`"];          src = "       #include \"WolframLibrary.h\"       #include \"time.h\"            DLLEXPORT mint WolframLibrary_getVersion(){         return WolframLibraryVersion;       }       DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData){         return 0;       }            DLLEXPORT int pause(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {         timer(MArgument_getReal(Args[0]));         return 0;       }            void timer(double seconds)       {         clock_t x;         x=clock()+seconds*CLOCKS_PER_SEC;         while(clock()<x){}       }            ";          test1 = CreateLibrary[src, "test1"];     pauseLib = LibraryFunctionLoad[test1, "pause", {Real}, Integer];          Table[pauseLib[1.],{8}];//AbsoluteTiming     (* {8.021739,Null} *)     ParallelTable[pauseLib[1.],{8}];//AbsoluteTiming     (* {2.350266,Null} *)


Check for holomorphy of a function

Given a (rather complicated) function `H(z)`, what is the best approach to check symbolically whether it is holomorphic? What I tried is checking explicitly the Cauchy-Riemann equations(*):               z = a + I b          H = E^-Sqrt[z^2] / (Sqrt[z^2] + Sqrt[z^2] Cosh[Sqrt[z^2]] + Sqrt[z^2] Sinh[Sqrt[z^2]])          HRe = FullSimplify[ComplexExpand[Re[H]], (a | b) ∈ Reals]     HIm = FullSimplify[ComplexExpand[Im[H]], (a | b) ∈ Reals]     HReA = Assuming[(a | b) ∈ Reals, D[HRe, a]]     HReA = Simplify[HReA, (a | b) ∈ Reals]     HImB = Assuming[(a | b) ∈ Reals, D[HIm, b]]     HImB = Simplify[HImB, (a | b) ∈ Reals]     Simplify[HReA == HImB, (a | b) ∈ Reals]      What I would expect as a result is either just `True` or some equation that `a` and `b` need to satisfy in order for the _CR_ equations to be fulfilled. This would mean that my function is not holomorphic everywhere in the complex plane. The problem that I encounter is that the call to `Simplify` does not complete computation in a reasonable amount of time (> 1 hour, then I aborted it). Checking whether `HRe` and `HIm` are harmonic (which is a necessary condition for `H` to be holomorphic) did not seem to be any easier, with the second derivatives of `H` being even longer. Is there a way to speed this up, or even a completely different approach? The derivatives are so long that a manual inspection is not an option. (*) Note that as correctly pointed out by murray below, the Cauchy-Riemann DEs being fulfilled alone does not already imply holomorphy. Additional properties need to be given, e.g. continuity of H or continuity of its derivatives.


How to make Mathematica Simplify?

Let us define               r1 = 1;r2 = 2;      and               beta2[t_] := {r1*Cos[2*Pi*t], r2*Sin[2*Pi*t]}     beta1[t_] := beta2[t + 4.8*t^2*(t - 1)^2]      k[v_] := If[Norm[v] > 0, v/Sqrt[Norm[v]], 0]      with               q2[t_] :=  FunctionExpand[k[beta2'[t]], Assumptions -> t \[Element] Reals]          q1[t_] :=  FunctionExpand[k[beta1'[t]], Assumptions -> t \[Element] Reals]      Now when I call                q1'[3]      I get {4.56985 + 0.157049 (10.2293 Derivative[1][Abs][-5.97566] - 40.9174 Derivative[1][Abs][-3.88322]), -28.1291 + 0.102057 (10.2293 Derivative[1][Abs][-5.97566] - 40.9174 Derivative[1][Abs][-3.88322])} **Question** > How to simplify this expression?


Permutations: selecting reviewers without conflicts of interest

I would like to automate the process of selecting a number of proposal reviewers that fit a conflict of interest criterion. Let's say I have 5 reviewers and 5 applicants from 5 departments. The department of a person can be obtained from the function `getdept`:               depts = { "science",  "language",  "art", "history",  "education"};     reviewers = { "mary", "jane", "bob", "joe", "john"};     applicants = { "mary", "pete",  "al", "fred", "patty"};     getdept[person_] :=       person /. {"mary" -> "science", "jane" -> "language",         "bob" -> "art", "joe" -> "history", "john" -> "education",         "pete" -> "language", "al" -> "art", "fred" -> "art",         "patty" -> "language"}      Each proposal must be read by three reviewers, none of whom can be from the same department as the applicant. I can generate a table of possible reviewers:               possrev =       Table[{i,         DeleteCases[reviewers, x_ /; getdept[x] === getdept[i]]}, {i,         applicants}]      And looking at the result in this trivial example, I can manually identify reviewers:               possrev[[All, 2]] // MatrixForm      ![Mathematica graphics](http://i.stack.imgur.com/0ZcPI.png) I'm stuck with how to select sublists. It looks to me as if I should end with a 3xN matrix where N is the number of applicants. No element in the resulting matrix would be represented more than three times. (We can assume that `Length[reviewers] >= Length[applicants]`). I suspect that there will not be unique solutions and I do not need all solutions (although that would be interesting). Is it possible to find a solution matrix, `assignments` such that:               Length/@Union/@assignments = 3      and               Count[Flatten[assignments], #] & /@ reviewers <= 3       [I think these are the correct mathematical representations of my criteria, but I may be mistaken.]


Are built-in Mathematica functions already parallelized?

I've been noticing something strange since updating to Mathematica 8, and that is that occaisionally I'll see that the MathKernel is using up to 800% CPU in my Activity Monitor on OS X (I have 8 cores). I have no Parallel calls whatsoever, and this is in a single kernel, not across multiple kernels. My code is pretty much only Interpolates, Maps, Do loops, and plotting routines. I'm curious if some of the built-in Mathematica routines are in fact already parallel, and if so, which ones?


Revert y-axis in RegionPlot

I have the following code:               Module[{n = 300, p = 0.29},        RegionPlot[{y > (1/2)*(n - x) && y + x <= n && y > p/(1 - p)*x},          {x, 0, n}, {y, n, 0}, FrameLabel -> {"x", "y"},          PlotStyle -> {Directive[Yellow, Opacity[0.5]]}]]      which will give you the yellow region on the LHS in the figure below. ![enter image description here](http://i.stack.imgur.com/KTtZC.png) **Question** : I want to revert the y-axis of the RegionPlot so that the axis will look like the RHS in the figure above and the position and the shape of the region change accordingly. This would be the first step to make a ternary RegionPlot.


FE`symbols that remain in notebook internals even after removing them and SaveDefinitions->True issue

How does one clear the notebook from symbols that remain in it after an edit session?


How to draw the axis with ContourPlot3D

I see ContourPlot3D doesn't show the X, Y, Z axis by default (i mean inside the graph), i tried adding ",Axis->True" to the call, but doesn't make effect. How to do this?


What is the right way to rotate an array?

Suppose I have an array, not necessarily square: a = $\left( \begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array} \right)$ I want to rotate it like one of these: $\left( \begin{array}{ccc} 3 & 6 & 9 \\ 2 & 5 & 8 \\ 1 & 4 & 7 \end{array} \right)$     $\left( \begin{array}{ccc} 7 & 4 & 1 \\ 8 & 5 & 2 \\ 9 & 6 & 3 \end{array} \right)$     $\left( \begin{array}{ccc} 9 & 8 & 7 \\ 6 & 5 & 4 \\ 3 & 2 & 1 \end{array} \right)$ I have been using:               a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};          Reverse[a, {2}]\[Transpose]          Reverse[a\[Transpose], {2}]          Reverse[a, {1, 2}]      Is there a cleaner, faster, or otherwise better way to do it? I am more interested in a general solution rather than a compiled solution for an integer array, but if you have a nice compiled approach please make it work on version 7.


How to get and set default font parameters for Plot, ListPlot, LogPlot, etc.?

How can I find the _default_ font parameters (family, size, etc.) for the text that appears in `Graphics` produced by `Plot`, `ListPlot`, `LogPlot`, etc.? I'm interested not only in the font specs used for axis and plot labels, but also (and importantly) in those for the numbers displayed next to tick marks. EDIT: At the moment there appears to be two entirely different ways to set these parameters, and it is not clear to me which one takes precedence. One, suggested by ybeltukov, is through `Format->EditStylesheet...`. The other one, described in the post linked to by Kuba, is through `SetOptions[Graphics, BaseStyle -> {...}]`.


Nested For loop with NDsolve

I am solving two simple differential equation using `NDsolve`.               solution = NDSolve[{X'[t] == μ*S[t]*X[t]/(k + S[t]),                          S'[t] == -μ*S[t]*X[t]/(0.664252*(k + S[t])),                         X[0] == 10,S[0] == 300}, {X, S}, {t, 0, 40.7}]      bacteria[t_] = X[t] /. solution;      food[t_] = S[t] /. solution;      qq = Table[310 - bacteria[t] - food[t], {t, time}];      error = MapThread[Plus,Abs[(exp[[All, 1]] - qq)/exp[[All, 1]]*100/298]]      I need to evaluate `error` for different values of `k` and μ in order to check the values of k and μ for which error is less than 5%. `exp` and `time` are results which I have. When I try to put my code in a For-loop, it fails.               For[μ = 0.1, μ <= 1, μ = μ + 0.1,       k = 100       solution = NDSolve[{X'[t] == μ*S[t]*X[t]/(k + S[t]),                            S'[t] == -μ*S[t]*X[t]/(0.664252*(k + S[t])),                            X[0] == 10, S[0] == 300}, {X, S}, {t, 0, 40.7}]       bacteria[t_] = X[t] /. solution;       food[t_] = S[t] /. solution;       qq = Table[310 - bacteria[t] - food[t], {t, time}];       error = MapThread[Plus,Abs[(exp[[All, 1]] - qq)/exp[[All, 1]]*100/298]]       Print[error]]      The above is giving me errors and I do not get any results. My plan is to use this For-loop to vary μ and then use a nested loop for varying k. Any comments?


Column specific data inputs

My data is in the form of 6 columns in a notepad file. I want to import, only from a specific column,say, the third column into Mathematica in the form of a list, i.e., i want commas to be placed after each data points. Thanks in advance!


why version 9 is much slower than version 8 in producing these graphics

Consider this example(taken from Thomas's question here)               rv = RandomVariate[ExponentialDistribution[2], 10^6];     t = AbsoluteTime[]; ListLinePlot[rv, PlotRange -> All]     AbsoluteTime[] - t (*Put this line into the NEXT cell,and evaluate \     both cells together*)          t = AbsoluteTime[];     Style[ListLinePlot[rv, PlotRange -> All], Antialiasing -> False]     AbsoluteTime[] - t (*This line in separate cell!*)      and this example (taken from a related question here)               ls = Table[Sinc[x*y], {x, -10, 10, 0.1}, {y, -10, 10, 0.1}];     ListPlot3D[ls, PlotRange -> All,        InterpolationOrder -> 2] // AbsoluteTiming      I get different performance in version 8 and version 9. Version 8 seems to be about twice as fast as version 9. Why this happens and how to make version 9 as fast as version 8? ![enter image description here](http://i.stack.imgur.com/eLrV8.png) ![enter image description here](http://i.stack.imgur.com/AwdOC.png)


Is it possible to find a limit of a sequence given by its recurrence relation?

I need to calculate a limit of a sequence given by its recurrence relation. I tried the following:               Limit[DifferenceRoot[Function[{y, n}, {           - n (1 + n)^2 (5 + 2 n) y[n]            - (1 + n) (3 + n) (11 + 14 n + 4 n^2) y[1 + n]            + (-77 - 128 n - 69 n^2 - 12 n^3) y[2 + n]            + (29 + 84 n + 79 n^2 + 30 n^3 + 4 n^4) y[3 + n]            + (3 + n)^3 (3 + 2 n) y[4 + n] == 0,            y[1] == 0, y[2] == -1, y[3] == 1/8, y[4] == -215/216       }]][n], n -> Infinity]      but it returned unevaluated.


The function `PowerExpand[z^(a+b)]` does not transform $z^{a+b}$ into $z^a z^b$. Is there a way to force Mathematica 8 to expand $z^{a+b}$ into $z^a z^b$? In this case, the particular reason why is because the Mod function does not simplify expressions very well. I end up having to expand the powers by hand. For example, this expression should simplify to zero,               2^(3 + 4 k) + 2^(7 + 8 k) - 81^(1 + k);         Assuming[Element[k, Integers] && k > 1, FullSimplify[Mod[PowerExpand[%],5]]]      > >     Mod[4 (2^(1 + 4 k) + 2^(5 + 8 k) + 81^(1 + k)), 5] >


Plotting a StateResponse inside a loop for some reason gives an error

/edit Nevermind i figured it out, i now have:                   Do[AppendTo[sr,         StateResponse[{StateSpaceModel[{amtrx[[i]], b, c, d}], {rad3,            rad4}}, M1[t], {t, 0, 5}]], {i, 9}];     Do[Print[Plot[sr[[i]][[1]], {t, 0, 5}, PlotLegends -> i]], {i, 9}]      and it works If have tried               Do[Plot[StateResponse[{StateSpaceModel[{amtrx[[i]], b, c, d}], {rad3,        rad4}}, M1[t], {t, 0, 5}][[1]], {t, 0, 5}], {i, 9}]      as well as `For[x = 1, x < 10, x++, Plot[StateResponse[{StateSpaceModel[{amtrx[[x]], b, c, d}], {rad3, rad4}}, M1[t], {t, 0, 5}][[1]], {t, 0, 5}]]` but for some reason i keep getting the following error: > StateResponse::nsymb: 0.00010214285714285715` must be a symbol. >> However, when i remove the Plot from the loop and instead use print, like so:               Do[Print[StateResponse[{StateSpaceModel[{amtrx[[i]], b, c, d}], {rad3,       rad4}}, M1[t], {t, 0, 5}]], {i, 9}]      it does give the output i expect, namely 9 times: > > {InterpolatingFunction[{{0.,5.}},<>][t],InterpolatingFunction[{{0.,5.}},<>][t]} so why when i want to build a Plot inside the loop does it break all of a sudden, and how do i fix this?


How to simplify an expression with square roots?

The expression $\sqrt{L^2 M+\sqrt{L^2 (-J^2 + L^2 M^2)}}/\sqrt{2}$，can be simplified into $\sqrt{L}(\sqrt{LM + J}+\sqrt{LM - J})/2$, but how can I obtain this result with _Mathematica_? That is, how can I simplify               Sqrt[L^2 M + Sqrt[L^2 (-J^2 + L^2 M^2)]]/Sqrt[2]      into               Sqrt[L]/2 (Sqrt[L M + J] + Sqrt[L M - J])


How to make each node of a graph a button?

A newbie question this one - MMA help seems to suggest it would be possible to place a button on ( or have a button be ) each node of graph, labelled with the name of said node. I have no idea where to start with the syntax for this though...any help much appreciated.


Integral converging in M9 but not in M10

**Background** : Mac OSX 10.9.4, Mathematica _9.0.1_ vs. Mathematica _10.0_ (both versions are Student Editions). I have a notebook. It used to evaluate fine in Mathematica _9_. I upgraded to _10_ and, without doing any modification at all to the notebook, an integral stopped converging. I even tried after quitting/restarting the kernel and doing an OS reboot. In an attempt to provide a minimal test case I wrote a code snippet that had a typo (epsilon instead of 'element of ') which caused a great deal of confusion. The code would not work, neither in _9_ nor _10_. Thanks to Michael for identifying it. The original code in my notebook did not suffer from this typo, although I'm afraid most people thought it did. * * * I narrowed the problem down to the following code:               ClearAll["Global`*"];     u[n_, x_] := If[x <= 0 || x >= L, 0, Sqrt[2/L] Sin[n π x /L]]     φ[n_, k_] =     Assuming[{n \[Element] Integers, L > 0},         Simplify@             (1/Sqrt[2 π]) Integrate[u[n, x] Exp[-I k x], {x, 0, L}]]          Δk[n_] :=     Assuming[{n \[Element] Integers},     Simplify@         ((Integrate[             φ[n, k]\[Conjugate] k^2 φ[n, k], {k, -Infinity, +Infinity}] -         Integrate[             φ[n, k]\[Conjugate] k φ[n, k], {k, -Infinity, +Infinity}]^2)^(1/2))]     L = 1;     (* If I replace ParallelTable[] with Table[], the problem disappears *)     ParallelTable[Δk[n], {n, 1, 1}]          (* If I uncomment the following line, the problem disappears no matter        whether I use ParallelTable[] or just Table[] *)     (*Quit[]*)          (* From now on it's the original code snippet I wrote with the typo fixed *)     ClearAll["Global`*"];     u[n_, x_] := If[x <= 0 || x >= L, 0, Sqrt[2/L] Sin[n π x/L]]          \[Phi][n_, k_] =     Assuming[{n \[Element] Integers, L > 0},         FourierTransform[u[n, x], x, k, FourierParameters -> {0, -1}]]          η[n_, k_] =         Assuming[{n \[Element] Integers, L > 0, k \[Element] Reals},             FullSimplify[                 \[Phi][n, k]\[Conjugate] \[Phi][n, k]]]          Δk[n_] =         Assuming[{n \[Element] Integers, n > 0, L > 0, k \[Element] Reals},         Simplify@Sqrt@             Integrate[k^2 η[n, k], {k, -\[Infinity], +\[Infinity]}]]      Mathematica _9_ yields $n\pi/L$ as a result for the last expression. In Mathematica _10_ I get a convergence error: ![enter image description here](http://i.stack.imgur.com/Uu9Ww.png) **Summary**   1. The problem is real.   2. The problem happens only when I use `ParallelTable[]` (instead of just `Table[]`).   3. The problem goes aways when I run `Quit[]` just before the 2nd `ClearAll` command.


Standard Deviation and StandardDeviationFilter

I found this scant description of `StandardDeviationFilter` in the documentation, implying one could use it to generate a moving standard deviation: ![enter image description here](http://i.stack.imgur.com/6nfMi.png) ![enter image description here](http://i.stack.imgur.com/TBagj.png) I've got a need for this sort of thing so it looked interesting. I tried the following comparision:               data = RandomReal[{-10, 10}, 1000];     sd1 = StandardDeviation[#] & /@ Partition[data, 50, 1];     sd2 = StandardDeviationFilter[data, 50];           ListLinePlot[{sd1, sd2[[-Length[sd1] ;;]]}, AspectRatio -> 0.25, ImageSize -> 600]     Length[#] & /@ {sd1, sd2}     sd1==sd2      which gives me the following output: ![enter image description here](http://i.stack.imgur.com/Gy7tB.png) I'd have guessed that the two approaches would give me the same output. Clearly not. Can anyone explain what `StandardDeviationFilter` does or doesn't do and why it differs from the expected? I may have missed something in setting up this comparison (it happens ;-), any ideas appreciated.


Green functions for recurrence equations

Is it possible to solve recurrence equasions in _Mathematica_ with the use of Green's functions and get a solution as a series?


Output format in MatrixForm

I have a correlation matrix, which I want to display in the following format:   * 2 decimal places (e.g., -0.56)   * number signs "+" and "-" (e.g., +0.76 or -0.34) I've tried many different things, but I had no success so far... The code I'm using to generate the data is:               randomWalk[x_] := Accumulate[Prepend[RandomVariate[NormalDistribution[0, 1], x], 0]]     exchange = Table[Subscript[asset, i] = randomWalk[500], {i, 1, 5}];      Now the code I'm using to generate the correlation matrix:               N[Correlation[Transpose[exchange][[1 ;; 500, All]]], 2]//MatrixForm      However, the numbers generated are displayed with `$MachinePrecision`, and not 2 decimal places (although I've used `N[#,2]`). I've tried another code:               MatrixForm[Round[Correlation[Transpose[exchange][[1 ;; 500, All]]], 0.01]]      In this case I get the correlation matrix with 2 decimal places, but it's still missing the "+" signal before the number. So I've tried this last code:               NumberForm[Round[Correlation[Transpose[exchange][[1 ;; 500, All]]], 0.01],NumberSigns -> {"-", "+"}]//MatrixForm      In this last case I get the numbers correctly formatted, but I'm not able to put them in `MatrixForm`. Can someone give me a hint to solve this?


How to Gather a list with some elements considered unique

I have a list of the form:               list={{0,...},{1,...},{1,...},{0,...},{3,...},{3,...},{0,...},{0,...},{5,...},{5,...},{5,...},{0,...},{5,...},{0,...},...}      So when we take all the first elements we get a run of integers:               list[[All,1]]     (* {0,1,1,0,3,3,0,0,5,5,5,0,5,0,...} *)      What I want to do is sort my list based on the first element of each sublist (the integers) by gathering the non zero integers but preserving the zeroes between them. So for this example for the sorted list the list of all first elements would look like this:               {0,1,1,0,3,3,0,0,5,5,5,5,0,0,...}      i.e. the second and subsequent occurrence of "5" get moved to join the earlier occurrences. Likewise for all other occurrences of integers -- they get moved up to join the first occurrence or group of occurrences. I am doing this in a round about way at the moment in which I record a list of positions after the reordering and then return `list[[positions]]`. I can post what I am doing at the moment but am interested to know if anyone has a one or two liner type solution. Also I wasn't quite sure how to title this question to make it easier for searches. Any ideas on that? **Edit** The integers will not necessarily appear in order. So, for example, the first appearance of a non zero integer could be ordered like               3, 1, 5, 4, 6, ...      The function below is what I am using to return the list of positions:               sortedPositions[list_List] :=        Module[{tmp = list[[All, 1]], length, pos, tmp1, tmp2,          tmp3},        length = Length[tmp];        tmp1 = List /@ Cases[Transpose[{tmp, Range[length]}], {0, _}];        tmp2 = DeleteCases[Transpose[{tmp, Range[length]}], {0, _}];        tmp3 = GatherBy[tmp2, First];        tmp2 = Join[tmp1, tmp3];        Flatten[SortBy[tmp2, #[[1, 2]] &], 1][[All, 2]]        ];      But it seems like a lot of code to get the result I need. Here is a test list:               num = 20;     testList = Join[List /@ RandomInteger[{0, 9}, num], RandomReal[{0, 1}, {num, 6}], 2]          (*      {{6,0.456203,0.0900917,0.62677,0.638615,0.227849,0.61252},     {4,0.317069,0.44889,0.456945,0.05121,0.940742,0.495415},     {7,0.573698,0.381817,0.859495,0.517238,0.459022,0.957771},     {5,0.832945,0.867634,0.0843833,0.296803,0.944986,0.563913},     {1,0.598743,0.803861,0.082542,0.138926,0.630364,0.0445202},     {7,0.289183,0.257115,0.358083,0.677393,0.206347,0.987678},     {5,0.947487,0.320408,0.600928,0.0718489,0.976703,0.449376},     {0,0.0996927,0.210278,0.408291,0.861885,0.946081,0.0522955},     {0,0.537572,0.160541,0.212737,0.508406,0.353786,0.479605},     {7,0.0815373,0.0677839,0.388955,0.681041,0.795607,0.404398},     {4,0.18704,0.253819,0.141732,0.43889,0.931269,0.556534},     {2,0.262136,0.110553,0.60296,0.482498,0.693049,0.430039},     {5,0.569696,0.262133,0.397575,0.246202,0.499777,0.073326},     {6,0.487893,0.121165,0.413376,0.874849,0.836484,0.792685},      {0,0.677934,0.543956,0.593967,0.138832,0.896184,0.604194},     {2,0.138691,0.150235,0.614355,0.326924,0.615902,0.900494},     {0,0.0254698,0.258354,0.377134,0.569083,0.0925844,0.672802},     {7,0.354392,0.976598,0.658138,0.124943,0.39485,0.239671},     {2,0.622461,0.195612,0.997663,0.421797,0.130802,0.110463},     {2,0.136431,0.799215,0.698071,0.0599957,0.452992,0.378609}} *)      Find the position order you want in your final list:               positions = sortedPositions[testList]     (* {1, 14, 2, 11, 3, 6, 10, 18, 4, 7, 13, 5, 8, 9, 12, 16, 19, 20, 15, \     17} *)      Make your "sorted" list "sorting" according to an algorithm applied to the first element:               testList[[positions]]     (*      {{6,0.456203,0.0900917,0.62677,0.638615,0.227849,0.61252},     {6,0.487893,0.121165,0.413376,0.874849,0.836484,0.792685},     {4,0.317069,0.44889,0.456945,0.05121,0.940742,0.495415},     {4,0.18704,0.253819,0.141732,0.43889,0.931269,0.556534},     {7,0.573698,0.381817,0.859495,0.517238,0.459022,0.957771},     {7,0.289183,0.257115,0.358083,0.677393,0.206347,0.987678},     {7,0.0815373,0.0677839,0.388955,0.681041,0.795607,0.404398},     {7,0.354392,0.976598,0.658138,0.124943,0.39485,0.239671},     {5,0.832945,0.867634,0.0843833,0.296803,0.944986,0.563913},     {5,0.947487,0.320408,0.600928,0.0718489,0.976703,0.449376},     {5,0.569696,0.262133,0.397575,0.246202,0.499777,0.073326},     {1,0.598743,0.803861,0.082542,0.138926,0.630364,0.0445202},     {0,0.0996927,0.210278,0.408291,0.861885,0.946081,0.0522955},     {0,0.537572,0.160541,0.212737,0.508406,0.353786,0.479605},     {2,0.262136,0.110553,0.60296,0.482498,0.693049,0.430039},     {2,0.138691,0.150235,0.614355,0.326924,0.615902,0.900494},     {2,0.622461,0.195612,0.997663,0.421797,0.130802,0.110463},     {2,0.136431,0.799215,0.698071,0.0599957,0.452992,0.378609},     {0,0.677934,0.543956,0.593967,0.138832,0.896184,0.604194},     {0,0.0254698,0.258354,0.377134,0.569083,0.0925844,0.672802}}      *)      So by "sorting"/"gathering" based on doing something with the first elements you do something like what I have tried to illustrate in the image below: ![enter image description here](http://i.stack.imgur.com/7F9nf.png) and create a new ordering of ultimately the initial list (`testList`) with the new order probably best seen by the new order of the first elements: ![enter image description here](http://i.stack.imgur.com/ULiP8.jpg) * * * As per Mr.Wizards answer what I am wanting to do is gather the list based on the first elements however I don't want to gather the zeros so only non-zero first elements are grouped.


Plotting a solution of the Allee Effect

I am doing a project on the Allee Effect. I am able to successfully create a stability analysis. That is, I can find the relevant equilibrium points ($y_e = 0,\ y_e = \alpha$ and $y_e=k$) and draw approximation curves. However, I am having trouble plotting the solution. The differential equation is $$ \frac{dy}{dx} = r y \left( 1 - \frac{y}{k} \right) \left(\frac{y}{\alpha} -1 \right) $$               sol = DSolve[y'[x] == r y[x] (1 - y[x]/k) (y[x]/a - 1), y, x]      Will produce the output: > >     {{y -> Function[{x}, >         InverseFunction[ >           Log[#1]/(a k) + Log[-a + #1]/(a (a - k)) + Log[-k + #1]/( >             k (-a + k)) &][-((r x)/(a k)) + C[1]]]}} >   where `a`, `r`, and `k` are constants depending on the population. When I try to plot `sol` using the code               Plot[Evaluate[y[x] /. sol /. {C[1] -> 1}], {x, -7, 7}, PlotRange -> All]      It will output an empty.I was told to use the manipulate function for the constants. Please can someone help.


Non-linear integral equation

I'm trying to solve with Mathematica an integral equation. I found this excellent answer (How to solve a non-linear integral equation?) solving with a collocation method a problem which can be restated as: $$ \int_a^b f \left( \phi \left(x \right) \right) \mathrm{d} x= 1 $$ for some function $f$, $\phi(x)$ being the unknown. My problem is slightly more complicated: $$ \phi(x) = \int_a^b K \left( x, y \right) f \left( \phi \left( y \right) \right) \mathrm{d} y $$ and the kernel $K(x,y)$ is singular for $x=y$, it behaves as $\sim \frac{1}{\left| x - y \right|}$. I would like to know if it is possible to extend the collocation method to this case, or, alternatively, which other methods can be used to numerically solve my integral equation. Thanks in advance! Edit: some more details: $$ f(\phi(x)) = \frac{\phi(x)}{\sqrt{\phi^2(x) + C^2}} $$ $$ K(x,y) = y \frac{\mathrm{e}^{-\left| x - y \right|}}{\left| x - y \right|} $$


How to assign a list of subsript?

I want to assign Subscript[C,i] by mapping a specific list. For example, the list is {1,2,3,4}, and I want to assign 1 to C1, 2 to C2, 3 to C3 and 4 to C4. How should I do? Many thanks:)


Successful match in Replace but not in Cases?

I have a little example that exhibits a successful pattern match in `ReplaceAll` that `Cases` misses and I wonder if the assembled sages would be so kind as to offer me an explanation? This is chopped from an original Prolog emulator by Renan Cabrera circa 2000.               ClearAll[k,s,l,m,j,f,w,g,a,b]      Consider an unordered sequence of _statements`s`_ stored in a _knowledge base`k`_, each being a _predicate`l`_ about some _terms`m`, `f`, `j`,_ and _`w`_ :               k=s[l[m,f],         l[m,w],         l[j,w],         l[j,m]     ];      We wish to search this knowledge base for any predicates such that `l[m,X_]` and `l[j,X_]`, where `X_` matches the same term in both predicates. Our first cut is something like               k /. s[l[m,X_],l[j,X_]] -> a[X]     (* Out[42]:= s[l[m,f],l[m,w],l[j,w],l[j,m]] *)      but this doesn't work until we make _s_ flat and orderless (associative and commutative):               SetAttributes[s,{Flat,Orderless}]      and now               k /. s[l[m,X_],l[j,X_]] -> a[X]     (* Out[43]:= s[a[w],l[j,m],l[m,f]] *)      This is, of course, just the same as `ReplaceAll[k, s[l[m,X_],l[j,X_]] -> a[X]]`. (notice the canonical reordering in the output), and now I can extract my answer with something like               Cases[k /. s[ l[m, X_], l[j, X_] ]->a[X],a[Y_]->Y]     (* Out[44]:= {w} *)      The surprise and the question is why doesn't this work?               Cases[k, s[ l[m, X_], l[j, X_] ] -> a[X]]     (* Out[45]:= {} *)      or even this               MatchQ[k, s[ l[m, X_], l[j, X_] ]]     (* Out[46]:= False *)      It's as though `ReplaceAll`, `Cases`, and `MatchQ` are using different pattern matchers. Will be grateful for advice, clues, discussion, etc.


Numeric function not fully evaluating

I'm running into an issue where it seems Mathematica is not fully evaluating the output of my function h[t_]. I included the definition of phi[t_] just to demonstrate that it is a numerically defined function in case that is what's causing the problem. This is causing the plot for h[t_] to turn up blank, because I guess the evaluation at each point is not numeric. Does anyone have some idea what's going on? I'm a bit of a Mathematica noob, I just recently switched from Maple which shit the bed so hard on a computation I was trying to do that I had to find an alternative software. Thanks! (Also, m,u,a are all defined as constants at the beginning of the notebook)               phi[t_] =       With[{a = E^-25, b = 1/4},         NDSolve[{x'[t] == (           8/20^4*(x[t])^2*(1 - a*E^(400*(x[t])^2)) - (6*(3/               10)^4*(1/20^2*((x[t])^2 - b^2) -                 1/20^4*(a*E^(400*(x[t])^2) - 1))))/((3/             10)^2*(3*(3/10)^4 - (4/                20^2*(1 - a*E^(400*(x[t])^2))) + (8*(x[t])^2*a*E^(                400*(x[t])^2)))), x[0] == 0}, x[t], {t, -140, 140}]][[1,All,2]]           h[t_] := N[(2*m^2*phi[t])/(3*u^2)*(1 - a*E^(phi[t]/m)^2)]          h[1]          (*  {0.000104884 (1. - 1.01291/e^25)} *)


Trying to prove that $x\sin(\frac{\pi}{x})\ge\pi \cos(\frac{\pi}{x})$ for $x\ge 1$

Consider the function               f[x_] := x Sin[Pi/x]      I want to prove that this function is increasing for $x\ge 1$. This can be done with the first derivative. We have to prove that $f'[x]\ge 0$ for $x\ge 1$. First I tried               FullSimplify[f'[x] >= 0, x >= 1]     (*Out: x Sin[\[Pi]/x] >= \[Pi] Cos[\[Pi]/x] *)      Then I realized that Mathematica probably doesn't know about the inequality $\tan(x)>x$ for $0<x<\pi/2$. So I tried:               FullSimplify[f'[x] >= 0, x >= 1 && ForAll[y, 0 < y < Pi/2, Tan[y] > y]]     (*Out: x Sin[\[Pi]/x] >= \[Pi] Cos[\[Pi]/x] *)      This inequality seems to be easy, I tried replacing `x >= 1` with `x >= Pi` and I get the same result. How can I properly use Mathematica to prove some theorems like this one? EDIT: The main point of the problem is not trying to prove that the function is increasing (that is the motivation of the problem) , the main point is trying to prove that $x\sin(\frac{\pi}{x})\ge\pi \cos(\frac{\pi}{x})$ for $x\ge 1$ using that $\tan(x)>x$ for $0<x<\pi/2$, i.e. i want to use the proving features of Mathematica.


How to plot CDF of a Poisson distribution in Mathematica

How to plot the following in Mathematica: $$P = \sum_{k=C+1}^{\infty}\frac{e^{-C^\gamma} (C^\gamma)^k}{k!}$$ I want to plot $P$ versus $C \log{C}$ for a given $\gamma$ with logarithmic scale on Y-axis. In Matlab, I'd calculate it as follows:               gamma = 0.75;     C = 1:1:20;     lambda = C .^ gamma;     p = 1 - poisscdf(C,lambda);     semilogy(C .* log(C), p);


Calculate integral in limit of very large coefficient

How I can calculate following integrals for large values $\alpha$ in Mathematica: $$ I_1 =\int_{0}^{y} \exp\left(\, -\alpha \sqrt{x(1-x)}\,\right)\, {\rm d}x $$ $$ I_2 =\int_{0}^{y} \exp\left(\, -\alpha \sqrt{x}\,\right)\, {\rm d}x $$


Definite Integral, Piecewise, Error

I am trying to evaluate the following:               myExpression=Piecewise[{{-c E^(c s)-(E^(-((-s+\[Alpha]+q \[Beta])^2/(2 (\[Beta]^2 \[Sigma]q^2+\[Sigma]s^2)))) v \[Beta])/(Sqrt[2 \[Pi]] Sqrt[\[Beta]^2 \[Sigma]q^2+\[Sigma]s^2]),\[Beta]!=0},{-c E^(c s),\[Beta]==0}}]     Integrate[myExpression,s]      However, when I try to make this Integral definite, by using {s,0,z}, I get the following error:               Integrate::pwrl: "Unable to prove that integration limits {0,z} are real. Adding assumptions may help"      I do not wish to change the expression of this integral, nor do I care for some cheap trick which removes the error message (like `Quiet`). I simply want to know where this error comes from, and what additional information about my variabales _Mathematica_ would like to know. Thanks! Laurens


How can I represent this automorphism of Q(i,a)?

Let $a$ represent some real irrational number. I am trying to perform computations with an automorphism $f:\mathbb{Q}(i,a)\to\mathbb{Q}(i,a)$ which fixes $\mathbb{Q}(i)$ pointwise and maps $a$ to $i a$. What's the best way to represent $f$? My approach below didn't work, since `f@f` performs a replacement on the symbol `f`:               f[x_] := x /. a -> I a     f[a]          (* I a *)          f@f[a]          (* -a *)          (f@f)[a]          (* I a (* Not the same as f@f[a] ?! *) *)      What's the best way to define `f` so that this does not happen?


How to work with large numbers

How do I browse very large numbers in mathematica, say $10^{{10}^{{10}^{1.414\ldots}}}$? By browse I mean finding the $k$th decimal place before or after the decimal point. Everything I have tried has given me `overflow[]` or something equally useless.


Algebra problem

I have recently run into an algebra problem that goes as follows. Using the numbers 1-9               A + B + C + D = EF     E + F + G + H = CJ     B + G + J = ?D     total = B?      where each letter is a different number. I believe when it says `EF` it does not mean `E*F` but more like if answer was `15`, then `E = 1` and `F = 5`. Been working on this for hours, even attempted to write a computer program to help solve but to no avail. Any tips on how to solve (or a work through of it) would be greatly appreciated.


Error when using EquationTrekker

I just got to know `EquationTrakker` because I need to do phase graphs for my classes. When I load it               << EquationTrekker`      everything works fine with no errors. However when I try to use an example of the documentation, I get:               EquationTrekker[y''[x] + y[x] == 0, y, {x, π/8, 2 π}]      > During evaluation of In[7]:= LinkObject::linkd: Unable to communicate with > closed link > LinkObject['/usr/local/Wolfram/Mathematica/10.0/SystemFiles/Java/Linux-x86-64/bin/java' > -classpath "/usr/local/Wolfram/Mathematica/10.0/SystemFiles… r > -Djava.util.prefs.PreferencesFactory=com.wolfram.jlink.DisabledPreferencesFactory > com.wolfram.jlink.Install -init "/tmp/m000004140851",480,4]. >> > > During evaluation of In[7]:= GUIRunModal::nvalid: The GUI definition > contains invalid content. >> > > During evaluation of In[7]:= LinkObject::linkn: Argument > LinkObject['/usr/local/Wolfram/Mathematica/10.0/SystemFiles/Java/Linux-x86-64/bin/java' > -classpath "/usr/local/Wolfram/Mathematica/10.0/SystemFiles… r > -Djava.util.prefs.PreferencesFactory=com.wolfram.jlink.DisabledPreferencesFactory > com.wolfram.jlink.Install -init "/tmp/m000004140851",480,4] in > LinkWrite[LinkObject['/usr/local/Wolfram/Mathematica/10.0/SystemFiles/Java/Linux-x86-64/bin/java' > -classpath "/usr/local/Wolfram/Mathematica/10.0/Syst… > a.util.prefs.PreferencesFactory=com.wolfram.jlink.DisabledPreferencesFactory > com.wolfram.jlink.Install -init "/tmp/m000004140851",480,4],<<1>>] has an > invalid LinkObject number; the link may be closed. >> >   >   >     $Failed >   How can I fix this? edit: forgot to mention I'm using Ubuntu 14.04. Haven't tried it on Windows 8 (dual boot) edit2: It works properly on Windows 8. It looks like it's a problem with any java package in ubuntu...


RegionPlot3D and Texture

I'm getting a white solid instead of a solid with texture, I'm not sure what is wrong:               RegionPlot3D[M, {a, -3, 3}, {c, -3, 3}, {d, -3, 3}, PlotPoints -> 100,       PlotStyle -> Directive[Texture[ExampleData[{"Texture", "Bricks2"}]]]      Here M is the solid defined by:               M:= (a < 0 && ((c < 0 && (d < 0 || d > -2 a - c)) || (c >              0 && (d < -c || d > -2 a)))) || (a >          0 && ((c < 0 && (d < -2 a || d > -c)) || (c >              0 && (d < -2 a - c || d > 0))))


How to determine three last bindings made to a variable when evaluating an expression?

How can I create a list of bindings made to a certain variable when evaluating an expression? I want to determine three bindings made.


Define an 'inner product' with AngleBracket

I want to define my own little 'Inner Product' function satisfying properties of linearity and commutativity, and I'd like to use the "$\langle$" and "$\rangle$" symbols to output my results. For this I am using `AngleBracket` which has no built-in meaning. I was able to use `SetAttributes[AngleBracket,Orderless]` to give my inner product the property of commutativity. $\langle v,w\rangle=\langle w,v\rangle$. Then I am able to inconsistently get the AngleBracket to distribute over addition using for example `Distribute[AngleBracket[u+v,w]]` But I am at a loss to impose the conditions $\langle a v, w\rangle=a\langle v,w \rangle$ where $a$ satisfies `NumericQ[a]==True`, and especially $\langle 0,v\rangle = 0$. How can do this? Do I need to write my own 'myInnerProductSimplify' function?


NonlinearModelFit with multiple parameters

I am now trying a slightly more complicated model which actually consists of finding the parameters of 2 particles in an Image (I attached an Plot of an image). Although I put very good initial values and constrains Mathematica wasn’t able to produce a result. Note at the final stage I will need to decompose the location of 4 particles...               J[i_, j_, α_, β_, xpos_, ypos_, clip_] := N[Clip[(β α^2*π)/ 4*((Erf[(j - xpos)/α ] - Erf[(j + 1 - xpos)/α ])*(Erf[(i - ypos)/α ] - Erf[(i + 1 - ypos)/α ])), {0, clip}]];     PixelImage[mat_]:=ArrayPlot[Rescale[mat,{0,Max[mat]},{Max[mat],0}],Epilog->{Red,MapIndexed[Text[#1,Reverse[#2-1/2]]&,Reverse[mat],{2}]},Mesh->True];     MyThreshold = 4043;     model1 = Clip[N[(β1 α1^2*π)/4*((Erf[(j - xpos1)/α1 ] - Erf[(j + 1 - xpos1)/α1 ])*(Erf[(i-ypos1)/α1 ] - Erf[(i + 1 - ypos1)/α1]))], {0,MyThreshold}];     model2 = Clip[N[(β2 α2^2*π)/4*((Erf[(j - xpos2)/α2 ] - Erf[(j + 1 - xpos2)/α2 ])*(Erf[(i -ypos2)/α2 ] - Erf[(i + 1 - ypos2)/α2]))], {0, MyThreshold}];     Model = Clip[(model1 + model2), {0, MyThreshold}];     data1 = Flatten[Table[{i, j, J[i, j, 0.7, 500, 6.5, 6.5, MyThreshold]}, {i, 1, 14}, {j, 1, 14}], 1];     data2 = Flatten[Table[{i, j, J[i, j, 0.6, 300, 4.5, 4.2, MyThreshold]}, {i, 1, 14}, {j, 1, 14}], 1];     Data = Transpose[{data1[[All, 1]], data1[[All, 2]], Clip[data1[[All, 3]] + data2[[All, 3]], {0, MyThreshold}]}];     PixelImage[Round[Partition[Data[[All, 3]], 14]]]          nlm = NonlinearModelFit[Data, {Model,         {0.4 <= α1 <= 0.8, 0 <= β1 <= 6000, 0 <= xpos1 <= 8,           0 <= ypos1 <= 8, 0.4 <= α2 <= 0.8, 0 <= β2 <= 6000,           0 <= xpos2 <= 8, 0 <= ypos2 <= 8}}, {{α1, 0.6}, {β1,           300}, {xpos1, 6.5}, {ypos1, 6.5}, {α2, 0.6}, {β2,           300}, {xpos2, 4.5}, {ypos2, 4}}, {i, j}, Method -> "NMinimize"];     nlm["BestFitParameters"]


Getting new symbols into Mathematica

What is the easiest way get new symbols into _Mathematica 9_? For example I want to be able to write the Symbol               \mathfrak{A}      that you have in _Latex_. I know that you can simply write an "A" in the notebook and change the font, so you get the right symbol. But this way you have to change between the font- window and the notebook window, and find the right font for your purpose. Favourably I would like to set a new pallet or integrate the symbol in the aliases or set a shortcut like `Cmd`+`Shift`+`A` for the symbol above I already tried to change the fonts of _Mathematica_ generally, so that the Symbol produces by "`Esc` `A` `Esc`" changes to `\mathfrak{A}` in _Latex_ , but did not get any satisfying result.


How to find this convolution?

How can I use _Mathematica_ to find the convolution $f*f$ for               f[t_]:=Piecewise[             {{t*(Pi - 4*t + t^2), Inequality[0, Less, t, LessEqual, 1]},               {(-t)*(2 + t^2 - 4*Sqrt[-1 + t^2] - 2*ArcCsc[t] + 2*ArcTan[Sqrt[-1 + t^2]]),                 1 < t < Sqrt[2]             }}, 0]      I would need a symbolic expression for the convolution. Thanks for any help.


Mathematica Package for Bayesian Networks

Are there any packages that allow the simulation of Bayesian Networks with Mathematica? I found what seemed to be a promising package (Dynamics) on a Brown University URL, http://www.cs.brown.edu/research/ai/dynamics/tutorial/Mathematica/ReadMe with an example notebook here http://www.cs.brown.edu/research/ai/dynamics/tutorial/Documents/GraphicalModels.html but unfortunately it seems that it is not included on their public FTP server. Thanks in advance...


Export graphics in parallel

I run a heavy simulation, using `NDSolve` and the method of lines. This means that the result of `NDSolve` is a list of, say, 400-1000 interpolation functions with many interpolation points. The whole thing can weigh up to 4GB. As it is, this poses no problem. The challenge is when I try to make a movie out the simulation. I do the following: I have a function               snapshot[sol_,t_]:=GraphicsGrid[{Plot[...],Plot[..],...}]      which take the result of `NDSolve` (what I call `sol`) and a specific time `t`, and makes some plots of the simulation at that time. Then, I export these graphics with something like               Table[       Export["~/tmp/" <> IntegerString[k, 10, 4] <> ".png",snapshot[sol, tList[[k]] ],     {k, 1, n}]      where `tList` is a list of times. Then I can make a movie out of the images with an external program (`ffmpeg`). The problem is that exporting the graphics like this takes a lot of time and I want to run it in parallel. Using `ParallelTable` is very bad, because it creates a local copy of the very heavy variable `sol` in all subkernels, and this immediately freezes my computer. I had no luck with `ParallelSubmit` or the like. Any ideas? _**EDIT**_ In response to all the commenters:   1. The plot is indeed local in the time variable.   2. I tried converting the `InterpolatingFunction`s to an numerical array. It saves some memory (a factor of ~50) but that's not enough - Still if you duplicate the data 1000 times (for 1000 frames) you'll be in bad shape. Basically, what I want is to send requests to **multiple processors** , but that will all run **on the same kernel**. This way you don't have to duplicate I thought it was possible because in MATLAB I do that naturally with the `parfor` command (or, at least, I think that's what I'm doing).


What's the best way to generate all the upper triangular matrix whose singular values are given?

For example, given $\lambda_1 = 1, \lambda_2 = 2, \lambda_3 = 3$, what's the best way to generate all the upper triangular matrix ($3\times 3$) whose singular values are $\lambda_i$? Note:Given a matrix $A$, if the eigenvalues of $A^HA$ are $\lambda_i \geq 0$, then $\sqrt{\lambda_i}$ are the singular values of $A$. $A^H$ is the conjugate transpose of $A$. Generally, If $B = U A V$ where $U,V$ are all unitary matrix, then $B$ have the same singular values of $A$.


Order items by closest to the previous

I have a list of 2D points (a table, imagine the data of a parametric plot shuffled) I would like to join the points with a line that starts from one of them and always goes to the closest one. I tried therefore to sort the points doing the following:   * take out the first element,   * search the closest in the remaining list   * bring it to the front   * recurse so that I can then use ListLinePlot As a first step I tried to do it in 1D (yes, in this case a simple sorting is sufficient, but not in the 2D case) However,I have a problem, because I do not know how to specify that a variable IS a list. Concretely               BringToFront =       Function[{list, pos}, Prepend[list[[pos]], Drop[list, {pos}]]]          BringClosestToFront =       Fuction[{list, val},        BringToFront[list, Nearest[list ->Automatic, val]]]          Follow[{}] = {};     Follow[list] =       Prepend[list[[1]],        Follow[BringClosestToFront[Drop[list, 1], list[[1]]]]]      And the BringClosestToFront is not accepted, with a               Part::partd: Part specification list[[1]] is longer than depth of object. >>      I am also worried of the speed of this recursive solution. Do you thing there may be a way to specify it in a more procedural way (i.e. implement insertion- sort)?


Adding a coordinate label to individual squares in ArrayPlot[...]

Can I write text, or add a specific text label to individual squares of an ArrayPlot[...] graphic? Specifically, I would like to assign an two- dimensional integer coordinate label to each square.


Inconsistent results of second derivative of inverse fourier transform

I am trying to get the Green's function of a toy diffusion equation $$\frac{\partial^2 u(x,t)}{\partial x^2} = \frac{1}{\alpha^2}\frac{\partial u(x,t)}{\partial t}$$ with _Mathematica_ 9. Then solve it by inverse Fourier transform:               u[x_, t_] := InverseFourierTransform[U[k, t], k, x]     D[u[x, t], {x, 2}]       D[D[u[x, t], x], x]           (* 0 *)     (* InverseFourierTransform[-k^2 U[k, t], k, x] *)       But can someone tell me why `Out[4]` and `Out[5]` are different? Thanks for your kindness.


Is there a way to print out SQL queries made using DatabaseLink?

I have a Mathematica batch script which makes some MySQL queries using DatabaseLink to store parameters of the run in a database. Recently, I had a run where these queries failed, and there was no output to indicate why. In the past, when I was using the SQLite interface, I had much success debugging (or at least recovering from errors) by printing out every SQL query made to the log file, but with functions like `SQLUpdate` and `SQLInsert` I don't get access to the raw queries. Is there a way I can get DatabaseLink to print them out for me, or at least get access to the raw query so I can print it myself?


Interpreting text entry and splitting it in a Manipulate text field?

I have the following program that plots the number of trigram appearances across a corpus of textual information between 1964 and 1989 (apologies for the messy code):               Manipulate[      viewerCount1 = {};      SetDirectory["/users/ME/desktop/DB/Put/"];      filenames = FileNames["*trigrams-put.txt"];      Do[       input = Get[file];       Clear[trigramHash];       (trigramHash[Sequence @@ #1] = #2) & @@@ input;       count = trigramHash[word1, word2, word3]; trigramHash[___] = 0;        AppendTo[viewerCount1, count];       , {file, filenames}];      DateListPlot[viewerCount1, {1964}, Joined -> True,        PlotLabel -> "Number of Trigram Appearances"], {{word1, "i",         "Word1:"}}, {{word2, "love", "Word2:"}}, {{word3, "you",         "Word3:"}}]      Right now, it looks like so: ![enter image description here](http://i.stack.imgur.com/KAHl4.png) What this is doing is initially seeing how frequent the phrase "i love you" is across files like this:               {{{"i", "don", "t"}, 102}, {{"i", "m", "gonna"}, 67},       {{"wa", "wa", "wa"}, 66}, {{"i", "can", "t"}, 66}, {{"i", "ll", "be"}, 66},       {{"i", "love", "you"}, 62}, {{"you", "don", "t"}, 55},       {{"la", "la", "la"}, 50}, {{"don", "t", "you"}, 49},       {{"don", "t", "know"}, 48}, {{"ain", "t", "that"}, 47},       The problem is that in this version you have to type word1 as `"i"`, word2 as `"love"`, and word3 as `"you"`. Would there be a way for _Mathematica_ to detect `"i love you"` in the `Manipulate` box, and then return responses as if it was `"i" "love" "you"`? So it could just be a phrase box, and it would split them in to three parts. (I have separate programs right now for unigrams, bigrams, trigrams, and quadgrams)


Show multiple plots with single variable

Using the same example code as in this question, is it possible to show all 10 plots (ie, each step of the manipulation) simultaneously? If a manipulate function is a series of listplots based on a single variable, is it possible to show all list plots simultaneously (ie - to overlay all listplots as one static plot). The only way I can think of doing this is copying & pasting the code n number of times, changing the variable for each one, naming each listplot & using               Show [a,b,c,d...]      but this seems fairly labour intensive!


How do I add new menuitems to menus?

What are some complete examples of what one would include in a FrontEnd `init.m` that would make use of `FrontEnd`AddMenuCommands` to add commands to the _Mathematica_ system menus (without having to directly edit `MenuSetup.tr`? For example, to do the following:   1. Add an item to the Help menu that brings up the `DocumentationCenter` window for Installed AddOns.   2. Add an item to the `Format > Background Color` sub-menu that would add a new color? Yes, I've already consulted MathGroup threads going back to 2009, and earlier, on modifying the startup menu by editing `MenuSetup.tr` and about evaluating, during a session, an expression to do a `FrontEndExecute`. But those messages don't seem to give a complete example of what I'm asking here.


Eigenvalue problem and plotting its eigenfunctions

How many different ways can one solve an eigenvalue problem and plot its corresponding eigenfunctions in Mathematica? For example for Harmonic Oscillator? Which one is the most accurate one? Thanks in advance.


Speed up manipulate by exporting each step as an image

Consider a manipulate function such as:               Manipulate[     per = 12.34;     pdata = Table[Sin[2 \[Pi] x/per], {x, n}] + RandomReal[.1, {n}];     ListPlot[pdata], {n, 100, 200, 10}]      which takes some time to re-evaluate each step of its manipulation. I would like to export each step of the manipulation as an image (rasterized or otherwise) & then create a manipulation that simply scrolls though the images, allowing it to run smoothly and quickly. Is there a way to automate something like this? _(NB The code I am working with takes far longer to re-evaluate each step that the example code above, but it works with much the same idea.)_


CycleIndex in v8

If I type               ?CycleIndex      I get > Information::notfound: Symbol CycleIndex not found. >> If I then type               Needs["Combinatorica`"]      I get > General::compat: Combinatorica Graph and Permutations functionality has been > superseded by preloaded functionaliy. The package now being loaded may > conflict with this. Please see the Compatibility Guide for details. Is there any good way to get the functionality I need without causing a conflict? The warning is somewhat strong and suggests nonspecific breakdowns further down the line...


Can I put tooltips in a Graph?

This doesn't work: ![Mathematica graphics](http://i.stack.imgur.com/8Usik.png) Is there a way to do this? My real goal is to identify the second links in the graph below, which shows the results of a webcrawl (using this code). I'm open to another approach. ![Mathematica graphics](http://i.stack.imgur.com/a7pwM.png)


Solving the Sine Gordon PDE in mathematica

how can i solve this equation in mathematica? this is sine-gordon eq. but the boundary condition can not recognized by mathematica . thank you for you attention.               NDSolve[{∂_(x,x) F[t,x]==(1-ζ)(Sin[F[t,x]]+β∂_t F[t,x]+∂_(t,t) F[t,x]),...     (∂_x F[t,x]==∂_t  F[t,x]/.x→0),(∂_x F[t,x]==∂_t F[t,x]/.x→1)},F,{t,0,10},{x,0,1}]      ## Edit:               \[Beta] = 1;     \[Zeta] = 1;     NDSolve[      {       D[f[t, x], x,          x] == (1 - \[Zeta]) Sin[[t, x]] + \[Beta] D[f[t, x], t] +          D[f[t, x], t, t],       D[f[t, 0], x] == D[f[t, 0], t],       D[f[t, 1], x] == D[f[t, 1], t]            },      f,      {t, 0, 10},      {x, 0, 1}      ]


How to get all possible orderings (equal ranks allowed) for given set of $N$ objects?

Hope there is a solution besides the tedious generation of nested loops. (Trying to avoid reinventing the wheel.) Here is an example with $N = 3$ objects. There are $13$ needed orderings (first `{}` means first place, second `{}` means second place, ...):               1. {a}, {b}, {c}     2. {a}, {c}, {b}     3. {a}, {b, c}     4. {b}, {a}, {c}     5. {b}, {c}, {a}     6. {b}, {a, c}     7. {c}, {a}, {b}     8. {c}, {b}, {a}     9. {c}, {a, b}     10. {a, b}, {c}     11. {a, c}, {b}     12. {b, c}, {a}     13. {a, b, c}      How can I get all such orderings for a given $N$? **UPD:** I also wonder how to get same orderings in binary relations notation, i.e., considering orderings as sets of ordered pairs (also neglecting here such pairs as $(a,a)$, $(b,b)$, ... since they don't make further difference). I found out that this notation is much easier way to further operating with rankings in _Mathematica_. Here are the above $13$ orderings in new notation:               1. {(a,b), (a,c), (b,c)}     2. {(a,c), (a,b), (c,b)}     3. {(a,b), (a,c), (b,c) (c,b)}     4. {(b,a), (b,c), (a,c)}     5. {(b,c), (b,a), (c,a)}     6. {(b,a), (b,c), (a,c), (c,a)}     7. {(c,a), (c,b), (a,b)}     8. {(c,b), (c,a), (b,a)}     9. {(c,a), (c,b), (a,b), (b,a)}     10. {(a,b), (b,a), (a,c), (b,c)}     11. {(a,c), (c,a), (a,b), (c,b)}     12. {(b,c), (c,b), (b,a), (c,a)}     13. {(a,b), (b,a), (a,c), (c,a), (b,c), (c,b)}


How do I find a weighted bipartite graph's minimum edge cover using Mathematica 8?

In graph theory, we use the Hungarian Algorithm to compute a weighted bipartite graph's minimum edge cover (a set of edges that is incident to every vertices, the one with the minimum total weight.) I find that in new version 8 of Mathematica, there is a whole new package of functions for Graph Theory, (begin with `Graph[]`.) But I've not found any function that do this job. I do find a function called `FindEdgeCover[]` that can only find a edge cover, not the minimum one.


About the number format in ticks

I want to `LogPlot` a function, but I have the trouble in the number format in the ticks. For example,               LogPlot[Abs[BesselJ[1, x] Sin[x]^2], {x, -10, 10},        Frame -> True, FrameTicks -> {{Automatic, None}, {None, None}}]      The output is ![Plot output](http://i.stack.imgur.com/NRMnW.jpg) If I use the command               LogPlot[Abs[BesselJ[1, x] Sin[x]^2], {x, -10, 10}, Frame -> True,         FrameTicks -> {         {{#, HoldForm[#]} & /@ {10^0, 10^-1, 10^-2, 10^-3, 10^-4, 10^-5}, None},         {None, None}        }     ]      I can get ![Plot output](http://i.stack.imgur.com/zoMBJ.jpg) Actually, I prefer the all the ticks in the form of `10^n`, and none of the commands shown above works. Is there any simple and clever way to cope with it? I'll be grateful for your reply.


how to deal with so many digits in plot ticks

the data is as follows               data = {{{25, 0.0000234834`}, {45, 0.0000127008`}, {65,      0.0000104495`}, {85, 9.68187`*^-6}, {105, 9.3519`*^-6}}, {{25,      0.0000210205`}, {45, 0.0000159071`}, {65, 0.0000148415`}, {85,      0.0000144786`}, {105, 0.0000143227`}}, {{25, 1.74304`*^-6}, {45,      1.74268`*^-6}, {65, 1.74261`*^-6}, {85, 1.74259`*^-6}, {105,      1.74258`*^-6}}, {{25, 4.26787`*^-6}, {45, 3.95165`*^-6}, {65,      3.88582`*^-6}, {85, 3.86343`*^-6}, {105, 3.85382`*^-6}}, {{25,      3.29821`*^-6}, {45, 3.1484999999999996`*^-6}, {65,      3.1174400000000003`*^-6}, {85, 3.1069`*^-6}, {105,      3.10239`*^-6}}, {{25, 2.4761199999999996`*^-6}, {45,      2.4761199999999996`*^-6}, {65, 2.4761199999999996`*^-6}, {85,      2.4761199999999996`*^-6}, {105, 2.4761199999999996`*^-6}}}      and               ListLogPlot[data]      gives ![img](http://i.stack.imgur.com/PE3Sp.png) There are some useless digits like "00000" in the tick. How to prevent this situation automatically? **Edit** I found an interesting thing, If you `Shift`+`Enter` the Plot again. Then the 00000 are gone and become scientific form. ![img2](http://i.stack.imgur.com/Zjn7T.png)


How can I manipulate the number of decimal places in the frame ticks?

Is there any simple way to increase or decrease the decimal places in the frame ticks. I want to make the y axis ticks of the first two and the second two graphs look similar. ![enter image description here](http://i.stack.imgur.com/YwVD5.png)


Adding a legend to a MatrixPlot

I have produced this MatrixPlot: ![](http://i.stack.imgur.com/OsIlG.jpg) Rows refer to countries and columns to ranks. Row 1 refers to Norway with many 1 ranks, row 15 to Greece with many 15 ranks. Other countries are inbetween. I would like to add a "Legend" to this plot, i.e. the string "Norway" should align (on the right side) with the first row etc. I have no idea how to accomplish this and any help would be appreciated.


Create colour with given lightness value

**How can I create a colour of my chosen hue with a given fixed lightness level?** For example, how can I create a reddish colour, `col`, so that `ColorConvert[col, "GrayScale"]` will return precisely `GrayLevel[0.6]`? Does Mathematica have something built-in to assist in this, or do I need to read up on how colours are converted between various representations? Note that the `b` value in `Hue[h, s, b]` does not correspond to the `GrayLevel` value. I need to have precise control over what certain colours I use will look like when converted to greyscale.


Lazy lists of Tuples and Subsets

I'm trying to build a lazy list that evaluates the n'th m-tuple or subset of a given list using Mathematicas ordering without calculating all the Tuples. The purpose is to allow for example the traversal of very large spaces of tuples without fist having to calculate the complete space of tuples. So far I have defined a function that calcluates which elements goes where for the n'th tuple:               tupleIndexes[l_, t_, n_] := Table[Mod[Quotient[n - 1, l^m] + 1, l, 1], {m, t - 1, 0, -1}]       And have used this to define a lazy list by defining a `SubValue` for when Part is applied.               lazyTuple /:Part[lazyTuple[list_, t_], n_Integer] /; 0 < n <= Length[lazyTuple[list, t]]:=        list[[tupleIndexes[Length[list], t, n]]]       The result is that `lazyTuple[{1,2,3,4},2]` remains unevaluted but `lazyTuple[{1,2,3,4},2][[2]]` returns `{1,2}` as expected. For testing I've defined a function to iterate through the list and return them all:               lazyTuple /: Length[lazyTuple[list_, t_]] := Length[list]^t     lazyTuple /: lazyTakeAll[a_lazyTuple] /; (NumericQ@Length@a) := Table[a[[i]], {i, Length@a}]      And it seems to check out:                lazyTakeAll[lazyTuple[Range@6, 3]] == Tuples[Range@6, 3]      > True Now my question is firstly if I'm making any subtle mistakes means this isn't returning the correct order with respect to `Tuples`. But more importantly, how would one go about defining a similar function for `lazySubsets[]`


How to clear variables in a manipulate without enabling dynamic content?

I have a series of variables that will plot the number of straight segments along a curve, thanks to the help from here on one of my previous questions. I can create a working Manipulate command from the code in Mathematica by varying nSeg and then visually show the number of segments increasing as the slider is raised, similar to the picture below. The number of segments (nSeg) can affect the number of x co-ordinates that I have, so if nSeg = 4 then I will have nSeg+1 x co-ordinates in total. ![Cable Arches](http://farm9.staticflickr.com/8443/7759685258_59e7b503b3.jpg) The difficulty I have is that because I am using subscripted variables for my x co-ordinates, if I try to reset them using the code below or through using Remove[] I invoke dynamic content in my Mathematica file and I'm unable to export as a CDF file that I can embed into a website, although I can get it to execute as a CDF if the user specifically selects to allow dynamic content.               clearSubscript[x_Symbol] := (First /@ Select[DownValues[Subscript],       MatchQ[First[#],         Verbatim[HoldPattern][Subscript[x, _]]] &]) /.      HoldPattern :> Unset;     clearSubscript[x];      I've been hunting around for ways to remove subscripted variables for a few days now, and whilst I've found a few different ways of doing it, I've not managed to work out how this can be done in a way that doesn't invoke Dynamic Content in Mathematica, and without doing this I'm struggling to create a CDF that can be embedded into a webpage. Any suggestions or help, gratefully received... EDIT: Removing all subscripts I still get a similar problem when trying to clear variables, edited to include simplified sample code below which I can't make into CDF file for embedding into a web page due to the Dynamic Content which I think is being invoked by the Clear command.                Manipulate[      nSeg;      f[x_] = (50 x)/41 - x^2/3362;      upVal = 4100;      chordL = Table[Sqrt[(x[i + 1] - x[i])^2 + (f[x[i + 1]] - f[x[i]])^2], {i, 1, nSeg}];      combEqs = # == d & /@ chordL;      Clear[vars, x];      vars = Append[{x[#], #, x[1] + 10^-6, upVal - 10^-6} & /@ Range[2, nSeg], {d, 1}];      x[1] = 0;      x[nSeg + 1] = upVal;      sol = {FindRoot[combEqs, vars]},      {nSeg, 3, 8, 1}      ]      Question updated to reflect the intention is to enable the Manipulate to recreate the graphical images above of the cable-chain arches, whilst I have no problems sharing the full code, I think it would be unfair to throw it all in here, but essentially there is a Plot function that plots the curves once the co-ordinates are calculated via the FindRoot, and the various solutions from the Findroot are also used to plot the links as straight lines. Combined with the proposed Dynamic and TrackedSymbols functions added, the code is something along the lines of:               Dynamic[     Manipulate[nSeg;     f[x_] = (50 x)/41 - x^2/3362;     upVal = 4100;     chordL = Table[Sqrt[(x[i + 1] - x[i])^2 + (f[x[i + 1]] - f[x[i]])^2], {i, 1, nSeg}];     combEqs = # == d & /@ chordL;     vars = Append[{x[#], #, x[1] + 10^-6, upVal - 10^-6} & /@ Range[2, nSeg], {d, 1}];     combEqs = combEqs /. {x[1] -> 0, x[nSeg + 1] -> upVal};     vars = vars /. {x[1] -> 0, x[nSeg + 1] -> upVal};     sol = {FindRoot[combEqs, vars]};     Show[Plot[f[x], {x, 0, 4100}],     Graphics[{Black, Thick,Line[Table[{{x[i], f[x[i]]}, {x[i + 1], f[x[i + 1]]}}, {i, 1, nSeg}] /. sol[[1]]]}],     Graphics[{Black, Dashed,Line[Table[{{x[i], f[x[i]]}, {x[i + 2], f[x[i + 2]]}}, {i, 1, nSeg - 1}] /. sol[[1]]]}],     Graphics[{Red, PointSize[Large],Point[Table[{x[i], f[x[i]]}, {i, 1, nSeg + 1}] /. sol[[1]]]}],     AspectRatio -> Automatic,     Axes -> False],     {nSeg, 3, 8, 1},     TrackedSymbols :> {nSeg}]]