echo off;
% NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1994
% To accompany the text:
% NUMERICAL METHODS for Mathematics, Science and Engineering, 2nd Ed, 1992
% Prentice Hall, Englewood Cliffs, New Jersey, 07632, U.S.A.
% This free software is complements of the author.

% Algorithm 2.4 (Approximate Location of Roots).
% Section 2.3, Initial Approximations & Convergence Criteria, Page 70
echo on; clc; format long; hold off; clear

% To approximately locate the roots of f(x) = 0 over [a,b].

% Define and store f(x) in the M-file f.m
% function y = f(x)
% y = exp(-x./10) + sin(x);

delete f.m
diary f.m; disp('function y = f(x)');...
disp('y = exp(-x./10) + sin(x);');...
diary off;

% Remark. f.m and approot.m are used for Algorithm 2.4
f(0); % Test for file f.m
pause % Press any key to see the graph y = f(x).

clc;
a = 0.0;
b = 30;
c = -1;
d = 2;
n = 100;
h = (b-a)/n;
X = a:h:b;
Y = f(X);
axis([a b c d]);...
plot(X,Y,'-g');...
hold on;...
plot([a b],[0 0],'b',[0 0],[c d],'b');...
xlabel('x');...
ylabel('y');...
title('Graph of y = f(x).');...
grid;...
axis;...
hold off;...
shg; pause % Press any key to continue.

clc;

% The abscissas are stored in the vector X.

% The ordinates are stored in the vector Y.

% Place the tolerance for a zero in epsilon.

epsilon = 1e-2;

R = approot(X,Y,epsilon);

pause % Press any key to see the approximate root locations.

clc; clg;
points = [R;f(R)];
n0 = length(R);
Z0 = zeros(1,n0);
axis([0 30 -1 2]);...
plot(X,Y,'-g',R,Z0,'o');...
hold on;...
plot([a b],[0 0],'b',[0 0],[c d],'b');...
xlabel('x');...
ylabel('y');...
Mx1 = 'Approximate root locations.';...
title(Mx1);...
grid;...
hold off;...
axis;...
shg; pause % Press any key to continue.

Mx1='The search interval is [';
Mx2='Number of subintervals used is n = ';
Mx3=[Mx1,num2str(a),','num2str(b),'].'];
Mx4=[Mx2,num2str(n)];
Mx5 = 'The approximate root locations are:';
Mx6 = [' x(k) f(x(k))'];
clc,echo off, diary output,...
disp(''),disp(Mx3),disp(''),disp(Mx4),disp(''),disp(Mx5),...
disp(''),disp(Mx6),disp(points'),diary off, echo on