function [sum] = trap(a,b,n) % Computes an approximation to the integral from a to b of % f(x) dx using the trapezoidal rule with n points. dx = (b-a)/n; sum = 0; for i=0:n, % Loop over nodes. x = a + i*dx; fx = f(x); % Evaluate integrand at x. if i==0 | i==n, sum = sum + .5*fx; % Add .5 * Value of integrand at endpoints else sum = sum + fx; % Add 1 * Value of integrand at interior points. end; end; sum = sum*dx; % Multiply final result by dx. %% Replace this function with the one you want to integrate. function fx = f(x) fx = cos(x.^2); return;