Writing a MATLAB script that implements the trapezoidal formula

3.8k Views Asked by At

I am aware that there is a trapz function in MATLAB but I have been set the task of creating a script that implements the trapezoidal formula for numerical integration.

Here is my attempt, unfortunately it is not working and help would be greatly appreciated:

% This program computes the integral of a function using the Trapezoid formula. If [a,b] is the interval of integration, then we introduce the partition a = x_0 < x_1 < x_2 <... < x_n =b

n = 10000; % Number of subintervals in [a,b].

a = 0; % Lower limit of integration.

b = 5; % Upper limit of integration.

del = (b-a)/n; % Length of each subinterval.

f = @ % The function I want to integrate

x = a:del:b; % The vector of the partition of [a,b]

xm = (a + del/2):del:(b -del/2); % The vector of the midpoints of the partition

y = 0.5*(f(a)+f(b)) + f(xm(1:n-1));

mp = del*sum(y) % These last two lines implement the formula

1

There are 1 best solutions below

0
On

I think in your codes the line

xm = (a + del/2):del:(b -del/2);

is redundant and in line

y = 0.5*(f(a)+f(b)) + f(xm(1:n-1));

f(a) and f(b) are scalars and f(xm(1:n-1) is a vector so you can not sum a scalar with a vector. So the codes should be as follows:

n = 100; % Number of subintervals in [a,b].

a = 0; % Lower limit of integration.

b = 5; % Upper limit of integration.

del = (b-a)/n; % Length of each subinterval.

f = @% The function I want to integrate

x = a:del:b; % The vector of the partition of [a,b]


y = 0.5*([f(a) 2*f(x(2:end-1)) f(b) ]);

mp = del*sum(y) % These last two lines implement the formula

Or instead of the last two lines(y and mp) use the following line

INT=del*sum(f(x(1:end-1))+f(x(2:end)))/2