0
$\begingroup$

I was trying to define a Piecewise function using a previously defined Interval object (that is the union of several intervals). However, I realised that I wasn't getting the right behaviour when trying to either plot or evaluate the function. If I define the function using the lower and upper limits of the interval everything works correctly though.

Here is a simplified version of my code:

f = Piecewise[{{1, Element[x, Interval[{0, 1}]]}}, 0]
g = Piecewise[{{1, 0 < x < 1}}, 0]

When running

Plot[{f, g}, {x, 0, 2}]

only g is plotted and not f. The same happens if I try to evaluate the functions at a specific x value.

Why is that the case? Is it possible to use Piecewise together with an Interval object or should I always use the upper and lower limits?

$\endgroup$

2 Answers 2

1
$\begingroup$
  • RegionMember work for Interval.
f = Piecewise[{{1, RegionMember[Interval[{0, 1}]]@{x}}}, 0];
g = Piecewise[{{1, 0 < x < 1}}, 0];
Plot[{f, g}, {x, 0, 2}, 
 PlotStyle -> {Directive[Red, Opacity[.2], AbsoluteThickness[10]], 
   Blue}]

enter image description here

  • When we want to use Element, we need to write such as Element[{1/2}, Interval[{0, 1}]] (*True *).
h = Piecewise[{{1, Element[{x}, Interval[{0, 1}]]}}, 0];
Plot[h, {x, 0, 2}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thanks! I still don't understand why Element doesn't work though. From the documentation on RegionMember: "Element can be used to test region membership for constant regions". Why is the [0,1] interval defined in my code example not considered to be a constant region? $\endgroup$
    – S -
    Oct 19, 2022 at 13:06
0
$\begingroup$
f = Piecewise[{{1, Between[x, Interval[{0, 1}]]}}, 0]
g = Piecewise[{{1, 0 < x < 1}}, 0]

Plot[{f, g}, {x, 0, 2}
 , PlotStyle -> {
   {AbsoluteThickness[5], Lighter@Yellow}
   , {Dashed, Blue}
   }
 ]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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