Integration in MATLAB

Ammar Ali Oct 19, 2021
Integration in MATLAB

This tutorial will discuss finding the integration of a function using the integral() function in Matlab.

Find the Integration of a Function Using the integral() Function in MATLAB

To find the integral of a given function, we can use Matlab’s built-in function integral. The input of the integral function is the input function, the minimum limit, and the maximum limit of the input function. For example, let’s define a function and find its integral using the function integral() in Matlab. See the code below.

MyFun = @(x) exp(-x.^3).*log(x).^3;
IntOfFun = integral(MyFun,0,Inf)

Output:

IntOfFun =

   -5.9765

We have used 0 as the minimum limit in the above code and infinity as the maximum limit. In the case of the parameterized function, we can pass the parameter value inside the integral() function. For example, let’s define a parameterized function with one parameter c and pass its value inside the integral() function. See the code below.

format long
MyFun = @(x,c) exp(-x.^3).*log(x).^3+c;
IntOfFun = integral(@(x) MyFun(x,6),0,2)

Output:

IntOfFun =

   6.023460235735111

We have used 0 as the minimum limit in the above code and 2 as the maximum limit. We can also specify other values inside the integral() function. For example, the output of the function integral() will be the integral of the input function concerning the default error-tolerant. You can also define other options in the integral() function, for example, the absolute error and relative error tolerance and tolerance waypoints. If you don’t define these variables, Matlab will use the default value for these variables. For example, let’s define the absolute error and relative error tolerance in the above code. See the code below.

format long
MyFun = @(x,c) exp(-x.^3).*log(x).^3+c;
IntOfFun = integral(@(x) MyFun(x,6),0,2,'RelTol',0,'AbsTol',1e-12)

Output:

IntOfFun =

   6.023460383922278

As you can see, in this case, the output is different as compared with the above output because, in this case, the value of absolute error and relative error tolerance is changed. You can also use the integral2() function to find the double integral of a function in Matlab. If you want to find the triple integral of an input function, you can use Matlab’s built-in function integral3().

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook