How to define a function by intervals in Mathematica?

Dunda picture Dunda · Oct 3, 2011 · Viewed 22.1k times · Source

How can I define a function f(x) in Mathematica that gives 1 if x is in [-5, -4] or [1, 3] and 0 otherwise? It's probably something simple but I just can't figure it out!

Answer

Simon picture Simon · Oct 3, 2011

The basic construction you want is Piecewise, in particular the function you were asking for can be written as

f[x_] := Piecewise[{{1, -5 <= x <= -3}, {1, 1 <= x <= 3}}, 0]

or

f[x_] := Piecewise[{{1, -5 <= x <= -3 || 1 <= x <= 3}}, 0]

Note that the final argument, 0 defines the default (or "else") value is not needed because the default default is 0.

Also note that although Piecewise and Which are very similar in form, Piecewise is for constructing functions, while Which is for programming. Piecewise will play nicer with integration, simplification etc..., it also has the proper left-brace mathematical notation, see the examples in the documentation.


Since the piecewise function you want is quite simple, it could also be constructed from step functions like Boole, UnitStep and UnitBox, e.g.

UnitBox[(x + 4)/2] + UnitBox[(x - 2)/2]

These are just special cases of Piecewise, as shown by PiecewiseExpand

In[19]:= f[x] == UnitBox[(x+4)/2] + UnitBox[(x-2)/2]//PiecewiseExpand//Simplify
Out[19]= True

Alternatively, you can use switching functions like HeavisideTheta or HeavisidePi, e.g.

HeavisidePi[(x + 4)/2] + HeavisidePi[(x - 2)/2]

which are nice, because if treating the function as a distribution, then its derivative will return the correct combination of Dirac delta functions.


For more discussion see the tutorial Piecewise Functions.