Message Boards Message Boards

0
|
38078 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How do you plot piecewise functions?

Posted 11 years ago
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.
POSTED BY: Ben Crain
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}]
POSTED BY: Isaac Abraham
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 BY: Himura Kazuto
Posted 11 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}]

POSTED BY: Mark Dooris
The other option..
Attachments:
POSTED BY: selahittin cinar
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