trapezoidal rule in matlab

The trapezoidal rule is a numerical integration method for approximating the definite integral of a function. It works by approximating the area under the curve of the function by a trapezoid with the same base as the interval of integration and whose sides are given by the function evaluated at the endpoints of the interval.

Here's an implementation of the trapezoidal rule in MATLAB:

main.m
function I = trapezoidal_rule(f, a, b, n)
% f: function to integrate
% a, b: integration bounds
% n: number of intervals

h = (b - a) / n; % width of each interval
x = a:h:b; % x-coordinates of each point

I = (h/2) * (f(a) + f(b) + 2 * sum(f(x(2:end-1)))); % integrate using trapezoidal rule
end
297 chars
11 lines

To use this function, you would pass in a function handle f, lower and upper bounds of integration a and b, and the number of intervals n. The function returns an approximation of the definite integral of f over the interval [a, b].

Here's an example of how to use the function:

main.m
>> f = @(x) exp(x);
>> I = trapezoidal_rule(f, 0, 1, 100);
>> disp(I);
1.7183
78 chars
5 lines

In this example, we're integrating the function exp(x) over the interval [0, 1] using 100 intervals. The output is the approximation 1.7183, which is approximately equal to the true value of the integral, e - 1.

gistlibby LogSnag