# Trapezoidal Rule with MATLAB Program Example

## Trapezoidal Rule Derivation

The derivation for obtaining formula for Trapezoidal rule is given by,

## Example

Evaluate the integral x^4 within limits -3 to 3 using Trapezoidal rule.

## Solution

Let y(x)=x^4

here a=-3 and b=3

therefore (b-a)=6

let ‘n’ be the number of intervals. assume n=6 in this case.

also h=(b-a)/n = 6/6 =1

x: -3 Â -2 Â -1 Â 0 Â 1 Â 2 Â 3

y: 81 Â 16 Â 1 Â 0 Â 1 Â 16 Â 81

According to trapezoidal rule:

## MATLAB Program forÂ Trapezoidal Rule

```%Created by myclassbook.org (Mayuresh)
%Created on 24 May 2013
%Question: Evaluate the integral X^4 within limits 3 to -3

clc;
clear all;
close all;

[email protected](x)x^4; %Change here for different function
a=-3;b=3; %Given limits
n=b-a; %Number of intervals
h=(b-a)/n;
p=0;

for i=a:b
p=p+1;
x(p)=i;
y(p)=i^4; %Change here for different function
end

l=length(x);
x
y

## Example

Evaluate the integral 1/(1+x) within limits 0 to 6 using Trapezoidal rule.

## Solution

Let y(x)=1/(1+x)

here a=0 and b=6

therefore (b-a)=6

let ‘n’ be the number of intervals. assume n=6 in this case.

also h=(b-a)/n = 6/6 =1

x: 0 Â  Â  Â  Â  Â  Â  Â  Â  Â 1 Â  Â  Â  Â  Â  Â  Â  Â  Â  Â 2 Â  Â  Â  Â  Â  Â  Â 3 Â  Â  Â  Â  Â  Â  Â  Â  Â 4 Â  Â  Â  Â  Â  Â  Â  5 Â  Â  Â  Â  Â  Â  Â  6

y:Â 1.0000 Â  0.5000 Â  0.3333 Â  0.2500 Â  0.2000 Â  0.1667 Â  0.1429

According to trapazoidal rule:

### MATLAB code for the Trapazoidal rule:

```%Created by myclassbook.org (Mayuresh)
%Created on 24 May 2013
%Question: Evaluate the integral 1/(1+x) within limits 0 to 6

clc;
clear all;
close all;

[email protected](x)1/(1+x); %Change here for different function
a=0;b=6; %Given limits
n=b-a; %Number of intervals
h=(b-a)/n;
p=0;

for i=a:b
p=p+1;
x(p)=i;
y(p)=1/(1+i); %Change here for different function
end

l=length(x);
x
y