Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function by intervals in Mathematica?

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!

like image 745
Dunda Avatar asked Oct 03 '11 04:10

Dunda


2 Answers

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.

like image 77
Simon Avatar answered Oct 29 '22 19:10

Simon


Although Simon's answer is the canonical and correct one, here are another two options:

f[x_] := 1 /; IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
f[x_?NumericQ] := 0

or

f[x_] := If[-5 <= x <= -3 || 1 <= x <= 3, 1, 0]

Edit:
Note that the first option depends on the order that the definitions were entered (thanks Sjoerd for pointing this out). A similar solution that does not have this problem and will also work correctly when supplied an Interval as input is

f[x_] := 0 /; !IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
f[x_] := 1 /;  IntervalMemberQ[Interval[{-5, -3}, {1, 3}], x]
like image 34
Dr. belisarius Avatar answered Oct 29 '22 17:10

Dr. belisarius