# How to set the value of constants in a function when plotting it

I have just begun learning Mathematica, so my apologies if my question is trivial. I did try to find it somewhere else but I didn't succeed.

Suppose I have a function $f(x)=A\ sin(x)+B\ cos(x)$. I would like to be able to plot this for a given value $A$ and $B$ that I determine when plotting. The pseudocode would be like this

Plot[A*Sin[x], {x,-10,10}, for A==5 and B==3]

Is it possible to achieve this? I would like to do so without using Manipulate.

• With[{a = 5}, Plot[a Sin[x], {x, -10, 10}]] Commented Jun 8, 2018 at 21:13
• Plot[a Sin[x]/.{a->5}, {x, -10, 10}]] Commented Jun 8, 2018 at 21:14

Correctly scoping variables is one of the trickiest parts of Mathematica.

You can write

With[{a = 5}, Plot[a Sin[x], {x, -10, 10}]]


but

f[x_]:= a Sin[x]
(* With[{a = 5}, Plot[f[x], {x, -10, 10}]] *) (* Won't work *)


you need

Block[{a = 5}, Plot[f[x], {x, -10, 10}]]

Plot[a Sin[x]/.{a->5}, {x, -10, 10}]]


or, in the case of the function:

f[x_]:= a Sin[x]
Plot[f[x]/.{a->5}, {x, -10, 10}]]


f[x_, a_, b_] := a Sin[x] + b Cos[x]

Plot[f[x, 5, 3], {x, -10, 10}]

• Yes, I guess that trick also works. But maybe it's not as pretty because you can confuse yourself which is meant to be a variable and which is not. Preference I think. Commented Jun 8, 2018 at 22:26

To avoid scoping issues, define the function to include the parameters as arguments.

f[a_, b_, x_] = a Sin[x] + b Cos[x];

Manipulate[
Plot[f[a, b, x], {x, -10, 10},
AxesLabel -> (Style[#, 14, Bold] & /@ {x, f[a, b, x]})],
{{a, 5}, Range[-5, 10], ControlType -> SetterBar},
{{b, 3}, Range[-5, 10], ControlType -> SetterBar}]