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.

  • 2
    $\begingroup$ With[{a = 5}, Plot[a Sin[x], {x, -10, 10}]] $\endgroup$ – mikado Jun 8 '18 at 21:13
  • 3
    $\begingroup$ Plot[a Sin[x]/.{a->5}, {x, -10, 10}]] $\endgroup$ – Fraccalo Jun 8 '18 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}]] 


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}]] 

How about this?

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

Plot[f[x, 5, 3], {x, -10, 10}]
  • $\begingroup$ 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. $\endgroup$ – Ptheguy Jun 8 '18 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];

 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}]

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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