1
$\begingroup$

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.

$\endgroup$
2
  • 2
    $\begingroup$ With[{a = 5}, Plot[a Sin[x], {x, -10, 10}]] $\endgroup$
    – mikado
    Commented Jun 8, 2018 at 21:13
  • 3
    $\begingroup$ Plot[a Sin[x]/.{a->5}, {x, -10, 10}]] $\endgroup$
    – Fraccalo
    Commented Jun 8, 2018 at 21:14

4 Answers 4

2
$\begingroup$

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}]]
$\endgroup$
0
0
$\begingroup$
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}]] 
$\endgroup$
0
$\begingroup$

How about this?

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

Plot[f[x, 5, 3], {x, -10, 10}]
$\endgroup$
1
  • $\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
    Commented Jun 8, 2018 at 22:26
0
$\begingroup$

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

enter image description here

$\endgroup$

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.