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!
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The basic construction you want is
Piecewise, in particular the function you were asking for can be written asor
Note that the final argument,
0defines the default (or “else”) value is not needed because the default default is 0.Also note that although
PiecewiseandWhichare very similar in form,Piecewiseis for constructing functions, whileWhichis for programming.Piecewisewill 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,UnitStepandUnitBox, e.g.These are just special cases of
Piecewise, as shown byPiecewiseExpandAlternatively, you can use switching functions like
HeavisideThetaorHeavisidePi, e.g.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.