% Generate the plot used on the final exam.

x0 = [10; 10];
global a = 1e-1;

function y = f(x)
  global a;
  y = -1/(1 + x(1)^2 + a*x(2)^2);
end

function y = df(x)
  global a;
  y = 2/(1 + x(1)^2 + a*x(2)^2)^2 * ...
      [x(1); a*x(2)];
end

xx = nlcg ('f', 'df', x0, 10, 1);  % CG with restart every second step 
z1 = xx(1,:) + i*xx(2,:);

xx = nlcg ('f', 'df', x0, 20, 0);  % Gradient method
z2 = xx(1,:) + i*xx(2,:);

xx = nlcg ('f', 'df', x0, 1, 19);  % CG without restart
z3 = xx(1,:) + i*xx(2,:);

title('Convergence history for a=10^-1');
xlabel('Iteration');
ylabel('Error');

semilogy (abs(z1), '-;Method A;',
	  abs(z2), '-*;Method B;',
	  abs(z3), '-@;Method C;')

gset term postscript eps monochrome;
gset output "convergence1.eps"
replot
gset term x11



