Numerical Integration
Goal: Build a numerical integrator in MATLAB that uses left Riemann summation, trapezoidal rule, and Simpson's rule to calculate the area of a function from x1 to x2.
Program Details: I will execute an M-file that is similar to the following code:
x1 = 1;
x2 = 3;
N = 20;
f = @(x) 0.2*x.^5 - 3*x.^2 - 5; % I will alter the first four lines of code
[LRiemArea, TrapArea, SimpsonArea] = CalcAreas(f, x1, x2, N);
IntegralArea = integral(f, x1, x2);
disp(['Left Riemann Area is ', num2str(LRiemArea)])
disp(['Trapezoidal Rule Area is ', num2str(TrapArea)])
disp(['Simpson's Rule Area is ', num2str(SimpsonArea)])
disp(['The integral() function gives ', num2str(IntegralArea)])
You will make an M-file named CalcAreas.m that contains a function named CalcAreas. This function calculates the area of the function f using the three techniques listed above. The M-file starts with the following line of code:
function [LRArea, TArea, SArea] = CalcAreas(f, x1, x2, N)
The input arguments are the anonymous function, the limits of integration x1 and x2, and the number of intervals N. The output arguments are the three areas of the three methods.
Additional considerations: If you need to create other functions to assist CalcAreas, put those functions in CalcAreas.m after the CalcAreas function. Suppress all output in CalcAreas using semi-colons. I don't want to see a lot of unnecessary output junking up my screen. Do not use the integral function in CalcAreas.
On your own: The error of the three methods usually decreases as N increases (x decreases). Vary N and notice how the resulting areas from the three methods compare to IntegralArea.