Let’s start with a simple function that we want to plot. We store an expression for the function in a variable.
In[]:=
MyFunc=aSin[x]
Out[]=
aSin[x]
If I now assign a value to one of the variables in my expression, it will get picked up if MyFunc gets evaluated again.
In[]:=
a=2;​​MyFunc
Out[]=
2Sin[x]
Now let’s plot it.
In[]:=
Plot[MyFunc,{x,-5,5}]
Out[]=
-4
-2
2
4
-2
-1
1
2
Let’s start over with the goal of using Manipulate to dynamically affect the plot. We’ll use a slightly different expression.
In[]:=
SomeFunc=kSin[tx]
Out[]=
kSin[tx]
Before we try the plot, let’s just see how Manipulate handles the expression.
In[]:=
Manipulate[​​SomeFunc,​​{k,-2,2},​​{t,-2,2},SaveDefinitions->True]
Out[]=
​
k
t
2Sin[2x]
You can see that k and t are not getting substituted in. Why? The k and t that we used to define SomeFunc were in the Global context. The k and t in the Manipulate are localized variables, which in Mathematica means that they use special names.
In[]:=
Manipulate[​​HoldForm[{k,t}],​​{k,-2,2},​​{t,-2,2},SaveDefinitions->True]
Out[]=
​
k
t
{FE`k$$5827960908668954914128748705099018674652,FE`t$$5827960908668954914128748705099018674652}
There’s no point in trying the plot, we know it will fail. So, what’s the solution? There are probably many ways to make this work, but one of the cleanest ways is to apply functional principles, in particular the notion of pure function. MyFunc and SomeFunc relied on global variables, in effect they relied on side effects. Change a in the Global context and all of a sudden MyFunc will output a different value the next time it’s evaluated. Let’s make a function. In Mathematica one common way to do that is by using DownValues (but there are other ways).
In[]:=
NiceFunc[k_,t_,x_]:=kSin[tx]
In[]:=
Manipulate[​​NiceFunc[k,t,x],​​{k,-2,2},​​{t,-2,2},SaveDefinitions->True]
Out[]=
​
k
t
2Sin[2x]
That looks promising, so let’s be bold and add the Plot.
In[]:=
Manipulate[​​Plot[NiceFunc[k,t,x],{x,-5,5}],​​{k,-2,2},​​{t,-2,2},SaveDefinitions->True]
Out[]=
​
k
t
-4
-2
2
4
-2
-1
1
2