MATLAB: How to perform double or triple integration in MATLAB

dblquaddoubleintegrationMATLABquadquadlquadvtrapztripletriplequad

Can I use the QUAD function to perform double or triple integration in MATLAB?

Best Answer

MATLAB provides several functions for the numerical evaluation of integrals. These functions are QUAD, QUADL, QUADV, DBLQUAD, and TRIPLEQUAD. Below is an example on how to implement a double integral using the DBLQUAD function. This shows how to solve the integral of f(x,y)dydx for the ranges of x going from xmin to xmax, and y going from ymin to ymax:
% This is the function to be integrated. 'y' is the inner
% variable and 'x' the outer variable. Note the order that
% the parameters are passed into the anonymous function
% “f”: inner variable first, then outer variable.
f = @(y,x) x*sin(y)+y*cos(x)
ymin = pi;
ymax = 2*pi;
xmin = 0;
xmax = pi;
result = dblquad(f, ymin, ymax, xmin, xmax);
The result is -9.8698, which is the correct result.
The first step is to build the function to be evaluated. The function must return a vector output when vector input is passed to it. You must also consider which variable is in the inner integral, and which belongs in the outer integral. In our example, the inner variable is y and the outer variable is x (the order in the integral is dydx).
The first argument is the handle of the integrand function. If you have defined this function as an anonymous function, no “@” symbol is required. The next four input arguments specify the limits of integration, and are:
ymin lower limit of inner integral
ymax upper limit of the inner integral
xmin lower limit of outer integral
xmax upper limit of the outer integral
Note that if you are using a version of MATLAB older than MATLAB 7.0 (R14), you will need to use a function file or an inline function. To use a function file, try the following:
function out = f(y, x)
% The first (inner) variable, y, is supplied directly by
% the 'quad' function. We pass x using the mechanism for
% supplying extra parameters to the integrand function.
out = x*sin(y)+y*cos(x); % The function to be integrated
Then, the integral can be evaluated using:
ymin = pi;
ymax = 2*pi;
xmin = 0;
xmax = pi;
result = dblquad(@f, ymin, ymax, xmin, xmax);
Also, note that the QUADV function was introduced in MATLAB 7.0 (R14), so it will not be available if you are using an older version.