% integrate.m
% C. Bishop, MAT 126, Fall 2020

% This MATLAB program computes left and right hand approximations
% to a given function f on an given interval [a,b].
% Values of f,a,b,n are given in lines of the program

% To run this open MATLAB in directory containing this file
% and type 'integrate' in the MATLAB command window. Change
% f,a,b,n by editing the file and re-saving before running again.

% the percent sign '%' denotes a comment in MATLAB

% CHOOSE WHICH FUNCTION TO INTEGRATE
%f=@(x) x.^2;
%f=@(x) exp(x);
%f=@(x) sin( pi*x);
%f=@(x) (sin(30*x).^2).*exp(-1./(1+5*x));
f=@(x) 1./x;
% CHOOSE LEFT AND RITH ENDPOINTS
a=1;
b=5;
%CHOOSE NUMNER OF SUBINTERVALS
n=10000;
% COMPUTE WIDTH OF SUBINTERVALS
delta=(b-a)/n;
% MAKE LIST OF PARITIONS POINTS X1, X2, ...
x=[a:delta:b];
% COMPUTE LEFT SUM
left=delta*sum(f(x(1:n)));
% COMPUTE RIGHT SUM
right=delta*sum(f(x(2:n+1)));
[left,right]
% CREATE FIGURE WINDOW
figure; hold on; grid on;
% PLOT FUNCTION IN BLUE
plot([a:.001:b],f([a:.001:b]),'b','LineWidth',3);
% DRAW BLACK AND RED SEGEMENTS TO SHOW LEFT AND
% RIGHT APPROXIMATIONS. DO NOT DRAW IF n > 100
if n < 101
for k=1:n
t=x(k);
s=x(k+1);
plot([t,t],[0,f(t)],'k','LineWidth',3)
plot([t,s],[f(t),f(t)],'k','LineWidth',3)
plot([t,t],[f(t),f(s)],'r','LineWidth',3)
plot([t,s],[f(s),f(s)],'r','LineWidth',3)
end % for k loop
end % if n < 101
% ADD LEFT AND RIGHT APPROXIMATIONS TO FUGURE IN TITLE
txt=['left = ',num2str(left),' right = ', num2str(right)];;
title(txt,'FontSize',25);
% text(a,f(b),txt,'FontSize',25,'Interpreter','latex')
return % end of program