% Métods de Aproximação em Engenharia - Mst. Eng. Construção
% Carlos Balsa - 2009/2010
% ficha nº 6 ex. 2

clear all

x1=-5:0.5:5;
x2=-4:0.5:15;
n1=length(x1);
n2=length(x2);

for i=1:n1;
  for j=1:n2;
f(i,j)=1/2*(x1(i)^2-x2(j))^2+1/2*(x1(i)-2)^2;
  end
end

% alinea a)
 clf;
 figure(1)
 mesh(x1,x2,f');
 xlabel('x1'); ylabel('x2'); zlabel('f(x1,x2)');

% alinea b)
 figure(2)
 contour(x1,x2,f',100)
 xlabel('x1'); ylabel('x2'); zlabel('f(x1,x2)');

% alinea c)
f=@(x) 1/2*(x(1)^2-x(2))^2+1/2*(x(1)-2)^2;
gf=@(x) [2*x(1)^3-2*x(1)*x(2)+x(1)-2 x(2)-x(1)^2]';
hf=@(x) [6*x(1)^2-2*x(2)+1 -2*x(1); -2*x(1) 1];
maxit=30;
tol=1e-4;
x0=[20 -20]';

[x, fx, k]=opt_newton(f,gf,hf,x0,maxit,tol)

return


% alinea d)

[x, fx, k]=opt_cg(f,x0,gf,hf,tol,maxit)
