This tutorial is about how to plot a piecewise function in MATLAB. In this tutorial, we will learn what a piecewise function is and the different ways to plot such functions in MATLAB. We will also see some examples for better understanding. We can implement piecewise functions by:

**Treating each function separately and merge and plot them on the same graph****If-else statement****along with for-loop****Switch-case statement****Using built-in function of Matlab which returns the piecewise function using a single-line command.**

Let’s discuss all these methods in detail along with their examples.

## Introduction to piecewise function

The piecewise function is a function defined by two or more two equations defined over different intervals. These multiple equations or pieces don’t need to be continuous and can be defined arbitrarily. For example:

The function behaves differently for different values of x. In the above example, when x is less than zero, the output f(x) is equal to 4x+3 while it solely depends on x for input values greater or equal to 0. Let us consider another example of piecewise function:

The above function on execution gives the graph in figure 1. The behavior of the graph changes with a change in the input (x). When x is less than -3, the graph is constant and after -3, it increases linearly with the x-axis. When x becomes greater than 3, the graph again becomes constant. The whole function is thus divided into three pieces.

Thus the piecewise function is the one whose domain is divided into multiple pieces and each piece has its own defined rules or constraints.

## piecewise function in matlab

The most basic way of implementing a piecewise function is to treat each equation of a piecewise function as a separate function and plot all of them on the same graph.

##### Example 1:

Consider a piecewise function f(x) having 4 intervals.

```
% The most Basic Method
clear all; close all; clc;
x1=-3:1:-1;
eq1 = (4*x1)+3; % Sub-function 1
x2=-1:1:1;
eq2 = x2; % Sub-function 2
x3=1:1:3;
eq3 = x3.^2; % Sub-function 3
figure
x = [x1 x2 x3];
y = [eq1 eq2 eq3];
plot(x, y)
xlabel('X-axis')
ylabel('Y-axis')
title('Piecewise Function f(x)')
grid on;
```

In the code given above, eq1, eq2, and eq3 represent the three equations whereas x1, x2, and x3 define the intervals for their respective equations. Then, we have created an array using all the intervals i.e., ‘x’ and an array of ‘y’ representing the different equation values. The plot(x, y) command then plots y against x. The graph in fig 2 shows the output obtained as a result of the plot(x, y) command.

**Output:**

#### using if-else statements

The second method involves the use of if-else statements along with for loop. In this method, we’ll define all the sub-functions along with the constraints using if-else statements and then we will plot the piecewise function.

##### Example 2:

Consider the following function:

```
% Plotting piecewise function using if else statements.
clc; clear all; close all;
% assign elements to x
x=-6:0.01:6;
%iterate over the elements in x one-by-one and calculate the value of f(x)
for i=1:length(x)
result(i)=piecewise_function(x(i));
end
% plot the values of y and x
plot(x,result)
xlabel('X-axis')
ylabel('Y-axis')
title('Piecewise Function f(x)')
grid on
hold off
% create a function to plot piecewise function
function result= piecewise_function(x)
if x <= 0
result = (-3*exp(x))+x;
elseif x>0 && x <= 2
result = x.^2;
elseif x>2 && x<=9
result = 4;
else
result = 0;
end
end
```

In this code, we have created an array “x” by using the colon operator. We can also use “linspace” command to create an array. The array x specifies the range of values on which we want to obtain the results of the piecewise function. Then, we have used a for loop which iterates over an array x and passes these values to the “piecewise_function”. The “piecewise_function” takes the value and check the conditions of if-else statements.

Here, if-else conditions are used to check the interval where the input(x) lies. Suppose x is equal to 2. As the value of x lies in the (0,2] interval, therefore, the x will enter into the body of the 2nd elseif condition. In this case, the body of the if statement consists of only one statement which is ” result = x.^2; “. Thus ‘result’ becomes equal to 4. The values calculated are stored into an array ‘result’ which represents the piecewise function values with respect to input (x). The plot(x, result) command plots the values in variable “result” against ‘x’.

**Output:**

**using switch-case statements**

It is almost similar to the above method but in this case, we have replaced the if-else with switch-case statements. We have separated the intervals of different sub-functions in different cases. First of all, the case expressions check the value of x. If the ‘case’ condition is true, then that means x lies in the interval specified by that case expression and the appropriate statements will be executed.

##### Example 3:

Considering example(2) again which is:

```
# Plotting Piecewise function using switch case statements
clc; clear all; close all;
x=(-6:0.01:6);
for i=1:length(x)
result(i)=piecewise_function(x(i));
end
plot(x,result)
xlabel('X-axis')
ylabel('Y-axis')
title('Piecewise Function f(x)')
grid on
hold off
function result= piecewise_function(x)
switch x
case x*(x <= 0)
result = (-3*exp(x))+x;
case x*(x>0 && x <= 2)
result = x.^2;
case x*(x>2 && x<=9)
result = 4;
otherwise
result = 0;
end
end
```

```
clc; clear all; close all;
x=(-6:0.01:6);
for i=1:length(x)
result(i)=piecewise_function(x(i));
end
plot(x,result)
xlabel('X-axis')
ylabel('Y-axis')
title('Piecewise Function f(x)')
grid on
hold off
function result= piecewise_function(x)
switch x
case x*(x <= 0)
result = (-3*exp(x))+x;
case x*(x>0 && x <= 2)
result = x.^2;
case x*(x>2 && x<=9)
result = 4;
otherwise
result = 0;
end
end
```

**Output:**

#### using built-in command

The MATLAB provides a built-in function “piecewise” which takes the equations and conditions as an argument and returns a piecewise expression. The syntax of this function is:

```
% Using builtin command
y = piecewise(condition1, expression1, condition2, expression2, .....)
```

##### Example 4:

Let’s understand this command by applying it to examples.

```
clear all;
close all;
clc;
syms x;
y=piecewise(-5<=x<=0,(2*x)+3, (0<x) & (x<2), x, (2<=x) & (x<=5),1-x);
fplot(y);
xlabel('X-axis')
ylabel('Y-axis')
title('Piecewise Function f(x)')
grid on;
```

**Output:**

It is the most efficient and recommended method as compared to the previous ones as it executes the piecewise function using only one command.

That’s why the two methods described above are not efficient. On the other hand, in the case of if-else and switch-case statements, as the number of conditions and equations inside the piecewise function increases so do the if-else statements and switch-case statements. For every new sub-function, you have to create a separate if-else condition or switch case condition which increases the length of a code. Whereas the ‘piecewise’ command shortens the multiple line code into a single line and is the most recommended method.

For further questions related to Matlab or Python Contact Us