8.2.1 Trapezoidal Rule
Using the definition of the trapezoidal rule
$\int_a^b f(x)dx \approx \frac{h}{2} \left[ f(x_0) + 2 \sum_{i=1}^{n-1} f(x_i) + f(x_n) \right]$
we can write a function traprule to perform trapezoidal rule integration. With the usual
index adjustment from 0-based to 1-based, we obtain the following function (you will need to
4
MXB103 Worksheet 8
Numerical differentiation and integration
replace the ?? with appropriate code):
function I = traprule(f, a, b, n)
%TRAPRULE Trapezoidal rule integration.
% I = TRAPRULE(F, A, B, N) returns the trapezoidal rule approximation for
% the integral of f(x) from x=A to x=B, using N subintervals,
% where F is a function handle.
if ~isa(f, 'function_handle')
error('Your first argument was not a function handle')
end
h = (b-a) / n;
x = a:h:b;
% an array of length n+1
S = 0;
for j = 2:n
S = S + ??;
end
I = h/2 * (?? + ?? + ??);
We will test this function on $f(x) = 1/x$, with $a = 1$, $b = 2$ and different values of $n$. The
answer to four decimal places is 0.6931.
>> f = @(x) 1/x;
>> traprule(f, 1, 2, 8)
ans =
0.6941