Message Boards Message Boards

GROUPS:

How do you plot piecewise functions?

Posted 7 years ago
19995 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 over
non-intersecting domains. A simple example:  f[x_]:= 2x - 3 for -4 <= x <= 1, and g[x_}:= -7x + 2 for 1 < x <= 5.
4 Replies
 (* 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}]
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}]]
]
Posted 7 years ago
Your functions can be combined into one well defined piecewise function, In the following {0,True) assigns the value zero to the function outside the defined intervals:
pw[x_] :=  Piecewise[{{2 x - 3 , -4 <= x <= 1}, {-7 x + 2 , 1 < x <= 5}, {0,True}}]
You can plot this (as desired). I have used ExclusionStyle to show the discontinuities:
Plot[pw[x], {x, -10, 10}, ExclusionsStyle -> {{Red, Dashed}, Blue}]

The other option..
Attachments:
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract