Trapezoidal
Rule
The code approximates the definite
integral of a function. The
integral is calculated using the trapezoidal
rule. Parameters of the function are the limits of integration
and the number of intervals
within the limits.
The function to be integrated is another parameter and must be defined
before running this program. For example, if we want to integrate the
function f(x)
= y
= x^{3}, we can define it, in Matlab,
like this:
function y = fun_for_integration(x)
y = x^3;
And then, we can create the integration function, like this:
function y = trap2(lower_lim, upper_lim, interv, fun)
% initialize
the result
y = 0;
% 'step' is
related to the size of each interval
step = (upper_lim  lower_lim) / interv;
% add up the
area of each trapezoid
for j = lower_lim : step : upper_lim
y = y + feval(fun,j);
end
% compute
integral
y = (y  (feval(fun, lower_lim) + feval(fun, upper_lim))/2) * step;
Now, we can call our integration function from another Matlab script or
from the command window, for example
z1 = trap2(0, 2, 10, 'fun_for_integration')
z2 = trap2(0, 2, 100, 'fun_for_integration')
z3 = trap2(0, 2, 1000, 'fun_for_integration')
and we get the Matlab results
z1 = 4.0400
z2 = 4.0004
z3 = 4.0000
Note that this is a numerical
integration, and so we have to be very aware of
the possible inaccuracies of the method. The first two
parameters given to the function are the lower and upper limits,
respectively. The third parameter is related to the size of each
interval: the higher the number the better accuracy in the evaluation
we can reach. The fourth parameter is the name of the function to be
integrated (the instruction 'feval'
is in charge of evaluating that function in the main body of the code).
Now, the best part is that Matlab has its own function to do the
integration using the trapezoidal rule ('trapz'), so we can
save all of our programming thinking for other things...
However, the builtin 'trapz'
function, works a little different. We first define our interval and
desired step in a variable vector x,
and define the value of the corresponding function in a variable vector
y.
For example, we want to evaluate the same function as above, within the
interval
[0 2], in 0.1 increments, so we use x = 0 : .1 : 2. If we want
a finer tunning of the integration function, we can set the step in our
independent variable. Then we can call the Matlab function like this
(three different cases)
x = 0 : .1 : 2;
y = x.^3;
z4 = trapz(x, y)
x = 0 : .01 : 2;
y = x.^3;
z5 = trapz(x, y)
x = 0 : .001 : 2;
y = x.^3;
z6 = trapz(x, y)
and we get the Matlab response, with different approximations
z4 = 4.0100
z5 = 4.0001
z6 = 4.0000
From
'Trapezoidal Rule'
to home
From
'Trapezoidal Rule' to 'Matlab Cookbook'

