% Modified Newtons Method
% Symbolic calculations
%
function ret = ModNewton(xx,niter)
tol = 1.0e-08; lowbound = 0; intvl = 1; ntrials = 20;
xx
nvar = length(xx);
for j = 1:nvar
    x(j) = xx(j);
end
as(1)=0;
xs(1,:)=x;
fs(1)=feval('Example6_1b',x);


syms x1 x2 f g1 g2 h
f = 3*sin(0.5 + 0.25*x1*x2)*cos(x1)
g1 = diff(f,x1)
g2 = diff(f,x2)
h = jacobian([g1;g2],[x1,x2])


for i = 1:niter -1

    %x1 = x(1); x2 = x(2)

    hval=subs(h,{x1 x2},{x(1) x(2)})
    grad = [subs(g1,{x1 x2},{x(1) x(2)}) subs(g2,{x1 x2},{x(1) x(2)})]'
    
    fprintf('Iteration: %2i\n',i)
    if grad'*grad <= tol
        fprintf('Exiting - FOC met !!!\n')
        break;
    end
    s = -inv(hval)*grad

    sv = double(subs(s,{x1 x2},{x(1) x(2)}))
    
    output = GoldSection_nVar('Example6_1b',tol,x, ...
        sv',lowbound,intvl,ntrials);

    as(i+1) = output(1)
    fs(i+1) = output(2)
%     for k = 1:nvar
        xs(i+1,:)=output(1,3:4);
        x(1,:)=output(1,3:4)

%     end
end


