Trapezoidal numerical integration in MATLAB
Trapz function in MATLAB is used to find the numerical integration using the trapezoidal rule. The basic idea in the Trapezoidal rule is to assume the region under the graph of the given function to be a trapezoid instead of the rectangle and calculate its area.
The formula for numerical integration using trapezoidal rule is:
where h = (b-a)/n
MATLAB allows us to perform numerical integration by simply using trapz function instead of going through the lengthy procedure of the above formula.
In MATLAB, trapz function takes the input arguments in 3 different ways.
In this method, trapz function considers unit spacing by default. Here Y is numeric data which can be a vector, a matrix, or multidimensional array.
- If Y is a vector, then trapz function computes the approximate integral of Y.
- If Y is a matrix, then trapz function integrates over each column of the matrix and returns a row vector of integration values as output.
- If Y is a multidimensional array, then trapz function integrates over the first dimension whose size does not equal 1.
Let’s take an example for calculating the integral of a vector Y containing function values for in domain [1,5]
In this method, X specifies the scalar spacing or the coordinates and trapz function integrates Y with respect to X.
- If X is a vector of coordinates, then the length of X must be equal to the size of the first dimension of Y whose size is not equal to 1.
- If X is scalar spacing, then the value of trapz(X,Y) is equivalent to X*trapz(Y).
Here below example demonstrate the trapz(X,Y) and calculate the integral value of vector Y having a point spacing value of pi/100.
Here, dim is the dimension to operate along and in this method, X is an optional argument.
- If dim is specified as 1, then trapz(Y,1) integrates over each column and returns a row vector of integration values.
- If dim is specified as 2, then trapz(Y,2) integrates over each row and returns a column vector of integration values.
The below example Integrates the rows of matrix Y with non-uniform point spacing with dim as 2 by using trapz(_____, dim) function.