function [f,fgrad] = func2d(x,y)
%
%  The function for exercise 5&6.
%  Remark: The function has two branches depending on the 
%  number of input arguments (nargin). If there is only one
%  input argument, it is assumed that x is a vector of length 2.
%  This alternative is used by the minimization routines (fmins).
%  Also the computation of the gradient is included in this 
%  alternative.
%
%  We need the second alternative to be able to pass also coordinate 
%  matrices as input parameters. Then, the output is the corresponding 
%  matrix of function values.
%
%  Input
%    x      argument of the function
%
%  Output
%    f      function value
%    fgrad  gradient
%

if nargin==1
  f = 100 * (x(2) - x(1).^2).^2 + (1 - x(1)).^2;
  if nargout==2,
     n = size(x);
     fgrad = zeros(n);
     fgrad(1) = -400 * x(1) * (x(2) - x(1).^2) - 2 * (1 - x(1));
     fgrad(2) = 200 * (x(2) - x(1).^2);
  end
elseif nargin==2
  f = 100 * (y - x.^2).^2 + (1 - x).^2;
end
