# How do you plot piecewise functions?

Posted 6 years ago
16517 Views
|
4 Replies
|
0 Total Likes
|
 Can you plot (on the same graph) a piecewise function in Mathematica? Not several functions over the same domain, but different  functions overnon-intersecting domains. A simple example:  f[x_]:= 2x - 3 for -4 <= x <= 1, and g[x_}:= -7x + 2 for 1 < x <= 5.
4 Replies
Sort By:
Posted 6 years ago
 (* Clear memory. *) Clear["Global`*"];  (* Define piecewise functions. *) f[x_] := Piecewise[{ {2x-3, -4 <= x <= 1} }]; g[x_] := Piecewise[{ {-7x+2, 1 < x <= 5} }];  (* Plot. *) Plot[ {f[x],g[x]}, {x, -5, 5}]
Posted 6 years ago
 This solution is not always works ideally. Somewhy Piecewise functions can have gaps while plotting. Check out this code, It can even be some faster MembershipFunction[center_, mid_] :=   Module[{S, pi},    pi[x_, a_, c_] := Piecewise[{           {S[x, c - b, c - b/2, c] /. {b -> (a + c)/2},     x <= c},            {1 - S[x, c, c + b/2, c + b] /. {b -> (a + c)/2}, x > c}}];   S[x_, a_, b_, c_] := Piecewise[{          {0, x < a},           {2 ((x - a)/(c - a))^2,    a <= x <= b},           {1 - 2 ((x - c)/(c - a))^2, b < x <= c},          {1, x > c}}];  a = 4 (3/4 center - mid);  ListLinePlot[Table[{x, pi[x, a, center]}, {x, 0, center*2, center/50}]] ]