The trapezoidal rule is a numerical integration technique used to approximate the definite integral of a function. It is a simple and widely used method that involves approximating the area under the curve of the function by approximating it as a trapezoid.

The basic idea of the trapezoidal rule is to divide the interval of integration [a, b] into a number of subintervals of equal width, and then approximate the area under the curve within each subinterval as a trapezoid with the two adjacent points on the curve as the endpoints of the base and the midpoint of the subinterval as the height. The sum of the areas of all the trapezoids gives an approximation of the integral.

The formula for the trapezoidal rule is:

∫(from a to b) f(x) dx ≈ (b-a) * [f(a) + f(b)] / 2 + ∑(from i=1 to n-1) [f(a + i * h)],

where h = (b-a)/n is the width of each subinterval, n is the number of subintervals, and f(x) is the function being integrated.

The trapezoidal rule is a first-order method, meaning that its error is proportional to the square of the width of the subintervals, or h^2. It is therefore less accurate than higher-order methods such as Simpson’s rule, but it is often faster and simpler to use.

## Trapezoidal Rule with MATLAB

```
% Numerical Analysis Trapezoidal Rule using MATLAB
clear all;
close all;
clc;
f=inline('1/(1+x^2)');
a=input('Enter lower limit of integral=');
b=input('Enter upper limit of integral=');
n=input('Enter number of intervals=');
h=(b-a)/n;
sum=0.0;
for i=1:n-1
x=a+i*h;
sum=sum+f(x);
end
trap=h*(f(a)+2*sum+f(b))/2.0;
fprintf('Evaluated Integral =%f',trap);
```

## Trapezoidal Rule with MATLAB using ‘`trapz`

‘ function

In MATLAB, you can use the `trapz`

function to apply the trapezoidal rule to approximate the definite integral of a function. Here’s an example:

Suppose you want to approximate the definite integral of the function f(x) = x^2 + 1 over the interval [0, 2]. You can use the `trapz`

function as follows:

```
x = 0:0.01:2; % define the x values
y = x.^2 + 1; % define the y values
integral_approx = trapz(x, y) % apply the trapezoidal rule
```

In this example, we define the x values from 0 to 2 with a step size of 0.01 using the colon operator. We then define the corresponding y values using the function `y = x.^2 + 1`

. Finally, we use the `trapz`

function to compute the approximate integral, which is stored in the variable `integral_approx`

. The `trapz`

the function takes two arguments: the x values and the corresponding y values.

You can adjust the step size by changing the third argument in the `x`

definition. A smaller step size will generally give you a more accurate approximation but will take longer to compute.

### Discover more from ReadsBlog

Subscribe to get the latest posts to your email.