2
$\begingroup$

I want to implement a condition to affects the behavior of a plot made in a Manipulate expression.

Suppose I have

Manipulate[Plot[Sin[nx],{x, 0, 5}],{n, 0, 6, 1}]

I want to change it so that for n odd, I get

 Manipulate[Plot[Sin[nx], {x, 0, 5}],{n, 0, 6, 1}]

and for n even I get

 Manipulate[Plot[Cos[nx], {x, 0, 5}], {n, 0, 6, 1}]`

But I want it in the same plot in the same Manipulate with n integer

How can I do this?

$\endgroup$
  • 1
    $\begingroup$ Lookup If / OddQ and it is n x not nx. $\endgroup$ – Kuba Nov 10 '17 at 13:42
2
$\begingroup$

You can do it by defining a new function

sincos[x_, n_?OddQ] := Sin[n x]
sincos[x_, n_?EvenQ] := Cos[n x]

which expresses your conditions. Then

Manipulate[
  Plot[sincos[x, n], {x, 0, 2. π}],
  {n, 0, 6, 1, AppearanceElements -> All}]

sin_1

cos_2

$\endgroup$
1
$\begingroup$

Another possibility is to use Which

enter image description here

Manipulate[
 Module[{f, x, title},

  Which[
   EvenQ[n], f = Cos[n x]; title = "cos(" <> ToString@n <> " x)",
   True, f = Sin[n x]; title = "sin(" <> ToString@n <> " x)"
   ];
  Plot[f, {x, -Pi, Pi},
   Frame -> True,
   FrameLabel -> {{"f(x)", None}, {"x", title}},
   GridLines -> Automatic, GridLinesStyle -> LightGray,
   PlotStyle -> Red,
   BaseStyle -> 14]
  ],
 {{n, 1, "n?"}, 0, 10, 1, Appearance -> "Labeled"}
 ]
$\endgroup$

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.