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
I think in your codes the line
is redundant and in line
f(a)andf(b)are scalars andf(xm(1:n-1)is a vector so you can not sum a scalar with a vector. So the codes should be as follows:Or instead of the last two lines(y and mp) use the following line