function NewtonExample
%% Optimal Control (EE-715)
% Course at EPFL
% Basic example of Newton´s method
%
%
% Autor:    timm.faulwasser@kit.edu
% Date:     20-07-16
% Status:   final

close all
clc

tol = 1E-10;
BREAK = 0;
 x = 1.3917452002707;
%x = 1;

z = [-2*pi:0.01:2*pi];
figure
plot(z, atan(z), 'g', 'Linewidth', 2);
hold on
plot(x, f(x), 'xb', 'Linewidth', 2);
hold on
grid on
display(['Residual f(x) = ', num2str(norm(f(x)))])


while BREAK == 0
  
    phi_k = f(x);
    dphi_k = df(x);

    d_k = -phi_k/dphi_k;

    x = x + d_k;

    % plotting 
    plot(x, f(x), 'xb', 'Linewidth', 2);
    hold on   
   
    % 
    display(['Residual f(x) = ', num2str(norm(f(x)))])
    reply = input('Compute next step? Y/N [Y]:','s');
    
    if norm(f(x)) < tol | reply =='N'
        BREAK = 1
    end
     
end

end


%% subfunctions
function phi = f(x)        
   phi = atan(x);
end
function dphi = df(x)      
   dphi = 1/(1+x^2);
end



