# Using piecewise defined functions in MATLAB

## Mathematical description

Suppose is equal to on the interval and on the interval and you want to define it as a MATLAB function. Use the unit step function or Heaviside function to define the piecewise function. This is the function in Section 6.3 of Boyce and DiPrima. It is defined by and . Then is 1 where and , so on the interval , and and it is 0 outside the interval. So

## How can you do this in MATLAB?

The unit step function is known to MATLAB as heaviside, with the slight difference that heaviside(0)=1/2.

## Example

Define a symbolic MATLAB function which is equal to if and is equal to if This is Boyce and DiPrima, Section 10.2 #19.

Solution:

syms x
f = -heaviside(x+2)*heaviside(-x)+heaviside(x)*heaviside(2-x)

f =

heaviside(2 - x)*heaviside(x) - heaviside(-x)*heaviside(x + 2)

## Check

You can check that this is right except at the and at 0 by plotting.

ezplot(f,[-2 2])
title('graph of f')

You can have MATLAB compute the values at and 0.

subs(f,x,-2)
ans =

-0.5000

subs(f,x,0)
ans =

0

At the value is and at 0 it is 0.