clear
clc
format compact
clf

%%
% Suppose we want to find a root of the function 
f = @(x) x.*exp(x) - 2;
fx = @(x) x.*0;

xr = [0 1.5];
fplot(f, xr)
xlabel('x') 
ylabel('y')
set(gca, 'ygrid', 'on')
title('Objective function')
hold on
fplot(fx, xr, 'k')
%%
% From the graph, it is clear that there is a root near x=1. So we call
% that our initial guess, x1.
x1 = 1
f1 = f(x1)
hold on

plot(x1, f1, 'o')

%%
% Next, we can compute the tangent line at the point
% (x1, f(x1)), using the derivative.
dfdx = @(x) exp(x).*(x+1);
slope1 = dfdx(x1);
tangent1 = @(x) f1 + slope1*(x-x1);
fplot(tangent1, xr, 'k--')
title('Function and tangent line')

%%
% In lieu of finding the root of f itself, we settle for finding the root
% of the tangent line approximation, which is trivial. Call this x2, our
% next approximation to the root.
x2 = x1 - f1/slope1
plot(x2, 0, '.')
f2 = f(x2)
title('Root of the tangent')

%%
% The residual (value of f) is smaller than before, but not zero. So we repeat the
% process with a new tangent line based on the latest point on the curve.
cla 
xr = [0.85 0.875];
fplot(fx, xr, 'k')
fplot(f, xr)
plot(x2, f2, '.')
slope2 = dfdx(x2);
tangent2 = @(x) f2 + slope2*(x-x2);
fplot(tangent2, xr, 'k--')
x3 = x2 - f2/slope2;
plot(x3, 0, '.')
f3 = f(x3)
title('Next iteration')

%%
% We appear to be getting closer to the true root each time
cla 
xr = [0.85 0.855];
fplot(fx, xr, 'k')
fplot(f, xr)
%plot(x2, f2, '.')
slope2 = dfdx(x2);
tangent2 = @(x) f2 + slope2*(x-x2);
fplot(tangent2, xr, 'k--')
x3 = x2 - f2/slope2;
plot(x3, 0, '.')
f3 = f(x3)
title('Next iteration')