function integral = trapezoidal_integration (fhandle, a, b, num_segments) %TRAPEZOIDAL_INTEGRATION Computes a definite integral % INTEGRAL = TRAPEZOIDAL_INTEGRATION ( FHANDLE, A, B, NUM_SEGMENTS ) % determines the integral of the function defined by FHANDLE between the % bounds of A and B. The integration interval [A,B] is divided into % NUM_SEGMENTS segments of equal width and the multiple application % trapezoidal integration rule is applied. % % Inputs: % FHANDLE: a Matlab function handle for the function to be % integrated. % A: Lower bound of the integration interval % B: Upper bound of the integration interval % NUM_SEGMENTS: the number of segments into which the interval is % divided to approximate the integral % % Outputs: % INTEGRAL: The result of the integration. % % Assumptions: % - The function is continuous and smooth. % - the function pointed to by FHANDLE supports vector operations % %% ME 2016 Section %% Fall 2007 %% %% AUTHOR: Chris Paredis %% % error checking % make sure the number of segments is a whole number larger than 0 num_segments = round(num_segments); if num_segments<1 error('the number of segments must be larger than or equal to 1'); end % compute the function values. % Note: the number of function values is num_segments+1 x_values = linspace(a,b,num_segments+1); f_values = fhandle(x_values); % make sure to use vector operations here! h = (b-a)/num_segments; % segment width % use the multiple application rule integral = h * (sum(f_values(2:end-1)) + 0.5*(f_values(1)+f_values(end)));