Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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

share|improve this answer
    
short and to the point, good explanation too. thank you for the answer :) –  user 3 50 Mar 1 at 18:35
add comment

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

share|improve this answer
    
A great answer as well, thank you :) –  user 3 50 Mar 2 at 20:01
1  
@user350 thanks, post for completeness –  ubpdqn Mar 3 at 10:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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