# Problems with Manipulating a piecewise function

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?

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.)

• short and to the point, good explanation too. thank you for the answer :) – user 3 50 Mar 1 '14 at 18:35

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"}] • A great answer as well, thank you :) – user 3 50 Mar 2 '14 at 20:01
• @user350 thanks, post for completeness – ubpdqn Mar 3 '14 at 10:05