0
$\begingroup$

I'm having problems with changing some parameters with "manipulate" in a piecewise function. The code i'm working with is:

f[x_] := -x /; x <= 0
f[x_] := 3 x + x^2 /; 0 < x <= 3
f[x_] := (-3 x + 28 + n) /; x > 3
Manipulate[Plot[f[x], {x, -5, 15}], {n, 0, 15, 1}]    

The problem is that if I leave the n the last part of the function won't even show up. Is there any easy way to fix this or is some extensive coding needed?

$\endgroup$

2 Answers 2

3
$\begingroup$

You need to include n as an input of your function:

f[x_, n_] := -x /; x <= 0
f[x_, n_] := 3 x + x^2 /; 0 < x <= 3
f[x_, n_] := (-3 x + 28 + n) /; x > 3
Manipulate[Plot[f[x, n], {x, -5, 15}, PlotRange -> {-30, 35},
  Exclusions -> {3}], {n, -15, 15, 1}]

This isn't an issue with piecewise functions, it's just an issue with manipulate. In your original version, the manipulate command doesn't understand how to plug in n=0, 1, 2, etc. into the function f[x], so it does nothing. THEN after the manipulate has tried to do the plot of f[x], and it does that, except now there is an n in your function that has cropped up (important) after the manipulate attempted to plug in for all the n symbols. That's why you should use the variable n explicitly.

(I also added an exclusion since you don't want a weird vertical line segment at x=3 and changed the plot range and manipulate range a bit. That's just style stuff.)

$\endgroup$
1
  • $\begingroup$ short and to the point, good explanation too. thank you for the answer :) $\endgroup$ Commented Mar 1, 2014 at 18:35
2
$\begingroup$

Just for completeness, the piecewise function can be defined using Piecewise. As pointed out by Kellen Myers, there is discontinuity at $x=3$. I have just 'joined the plot'.

f[x_, n_] := Piecewise[{{-x, x <= 0},
   {3 x + x^2, 0 < x <= 3}, {-3 x + 28 + n, x > 3}}];

Visualizing:

Manipulate[
 Plot[f[x, n], {x, -5, 15}, Exclusions -> None, 
  PlotRange -> {0, 40}], {n, 0, 15, 1, Appearance -> "Labeled"}]

enter image description here

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.