New to Mathematica. I want to be able to input some parameters, do some calculations, and end up with some output in a functional form such as:

f = a*Cos[x] + b*Sin[x] + ...

with coefficients a,b,..., then I want to use Manipulate to plot f as a function of x automatically and control these coefficients a and b with sliders without copying the functional form or the sliders (i.e. {a, 0, 1}, {b, 0, 1},...) into the argument of PolarPlot and Manipulate:

Manipulate[PolarPlot[a*Cos[x] + b*Sin[x] + ... ,{x, 0, 2Pi}], {a, 0, 1}, {b, 0, 1},...]

In my case, I have 81 possible coefficients to start, but in most cases the resulting functional form only depends on a few of these coefficients, and thus I don't want to have 81 sliders when my function only depends on 2 of them.

For example, I want to do something like this:

variables = DeleteDuplicates@Cases[f, _Symbol, Infinity];
In[]:= variables
Out[]: = {a,x,b}
g[variables_] = f; 
(*this doesn't work, but I want to assign all the variables a, x, b as inputs to a function g*)

coefficients = Delete[variables, Position[variables, x]];
coeffrangelist = Array[c, Length[coefficients]];
For[i = 1, i < Length[coefficients] + 1, i++, coeffrangelist[[i]] = {coefficients[[i]], 0, 1}];
In[]:= coeffrangelist
Out[]: = {{a, 0, 1}, {b, 0, 1}}

Manipulate[PolarPlot[g[variables],{x, 0, 2Pi},coeffrangelist]] 
(*this also doesn't work, but I want to generate an input for sliders for coefficients that are present*)

And thus for a different set of inputs to the code and a different function f being generated, let's say now including coefficients a,b,d,c,e the code still generates the plot of f(x), but now with sliders for a,b,c,d and e.

Any advice here would be greatly appreciated. Thanks.


1 Answer 1


Please try this code. Assuming it works for you feel free to ask for clarification as needed.

f = a*Cos[x] + b*Sin[x];

vars = Variables @ Level[f, {-1}];
pats = Pattern[#, _] & /@ vars;

g[pats] = f;

coeff = DeleteCases[vars, x];
ranges = {#, 0, 1} & /@ coeff;

With[{body = g[vars]},
  Manipulate[PolarPlot[body, {x, 0, 2 Pi}], ##] & @@ ranges

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.