% Mat-1.3379 Dynaamisten systeemien erikoiskurssi Eirola/Hannukainen
%
% Gauss-Newton
%
% x0   = initial guess
% fun  = function handle to f
% dfun = function handle to Df 
% Ifun = function handle to Df^I 
%
% if no Ifun is specified => use QR-decomposition is used to
% compute  the right inverse.
% 
% X = matrix of the iteration steps.


function [x,X,No]=gnewton(x0,fun,dfun,Ifun)


% make sure x0 is a column matrix 

x0 =x0(:);

% if Ifun is not specified => use QR-decomposition !

if(nargin < 4)
  Ifun = @qrifun;
end

% set tolerance 

tol = 1e-11;
maxIter = 10;

% iterate !

X = x0;

x = x0;
No =[norm(fun(x))]

for i=1:1:maxIter

  % update x
  x = x - Ifun(dfun(x),fun(x));
  
  % save iteration step
  X = [X x];
  
  % check tolerance
  No = [No norm(fun(x))]
  if norm(fun(x)) < tol
  
    disp('tol - reached');
    return;
    
  end
  
end

disp('maxIter reached');




  


  


 