<< Chapter < Page | Chapter >> Page > |
height = (y(n) + y(n-1))/2; %average height of function across interval
base = x(n) - x(n-1); %length of interval
The area, as in Equation [link] , is base times height. The height is the average of the height of the function at the two corner points. The length of the interval is the difference between the two corner points.
Lastly, we compute the area of the trapezoid and add it to our answer:
trap_area = base * height; %area of trapezoid
curve_area = curve_area + trap_area; %add to continuing sumend
The
end
statement closes the loop over triangles.
To check the accuracy of our code, we test it with many examples, one of which is shown here. The function
trapz()
is a built-in function that performs the same operation:
>>x = 0:.01:pi;>>y = sin(x);>>mytrapz(x,y)ans = 1.99998206504367>>trapz(x,y)ans = 1.99998206504367
Additionally, we know that , so the answer we are getting is very close to the true value.
A simpler implementation of the code is included at the end, if we specify a third argument `
fast
':
%alternate (fast) implementation
curve_area = sum(y(2:end-1).*(x(3:end) - x(1:end-2)));curve_area = curve_area + y(1)*(x(2) - x(1)) + y(end)*(x(end) - x(end-1));
curve_area = curve_area/2;
The explanation for this code is left as exercise 2.1.
The trapezoid rule is a way of estimating the area under a function. This is exactly what we call an integral . The integral of from to looks like this:
For well-behaved functions, evaluation of the trapezoid rule approaches the true value of the integral (true area underneath the curve) as we evaluate smaller and smaller intervals. Of course, there are other ways to characterize integration, namely the Fundamental Theorem of Calculus . For more on this, see the Connexions module Integration, Average Behavior: The Fundamental Theorem of Calculus .
2.1 Show that Equation [link] is equivalent to the “fast" version of the code:
2.2 Test the accuracy of
mytrapz.m
for
(or some other function) as you increase the number of trapezoids. Plot your result on a
loglog()
plot: on the
-axis, number of trapezoids, and on the
-axis, error.
We now introduce the key mathematical ideas that will allow us to break down signals into their component frequencies.
Suppose the function consists of several sine waves added together:
Suppose we know over some interval, say , and we want to find . Before we jump into this, we need to calculate the value of a certain integral. For integers and , with ,
If instead ,
Notification Switch
Would you like to follow the 'The art of the pfug' conversation and receive update notifications?