function varargout = problem(x,flag,par)
%
%     Problem function.
%
%     VAR = PROBLEM(X,FLAG,par) computes the problem function f(X),
%       Jacobian df/dx(X),startvector for the Gauss-Newton
%       iteration and vector of to be fitted values.
%
% FX = PROBLEM(X,'',par)          
%    returns the right hand side f(X) for a input column vector X.
% JAC = PROBLEM(X,'jacobian',par) 
%    returns the Jacobian df/dx(X) for a input column vector X.
% [X0,OPTIONS] = PROBLEM(X,'init',par)
%    returns a startvector X0 and problem specific solver options OPTIONS which
%    should override any solver default options. For more help on OPTIONS, see
%    help nlscon.
%   
%
 switch flag
 case ''                                 % Return y = f(x).
   [varargout{1:2}] = f(x) ;
 case 'jacobian'                         % Return Jacobian matrix df/dx.
   [varargout{1:2}] = jacobian(x);
 case 'init'                             % Return default [x0,options].
   [varargout{1:3}] = init(x) ;
 otherwise
   error(['Unknown flag ''' flag '''.']) ;
 end

% --------------------------------------------------------------------------
 
function [r,fail] = f(x)
   r=zeros(12,1) ;
   r(1)=x(1)-x(2)^2-x(3)^2+100.0 ;
   for i=2:12
     h =(2.0*(i-2.0)-x(3))/x(2) ;
     r(i)=x(1)*exp(-h*h/2.0) ;
   end
   fail = 0;

% --------------------------------------------------------------------------
 
function [J,fail] = jacobian(x)
   fail = 0;
   J(1,1)=1.0 ;
   J(1,2)=-2.0*x(2) ;
   J(1,3)=-2.0*x(3) ;
   for i=2:12
     h =(2.0*(i-2.0)-x(3))/x(2) ;
     exph = exp(-h*h/2) ;
     hexph = x(1)*exph*h/x(2) ;
     J(i,1)=exph ;
     J(i,2)=hexph*h ;
     J(i,3)=hexph ;
   end

% --------------------------------------------------------------------------
 
function [x0,fit,options] = init(x)
   x0 = [1.0 2.0 5.0]' ;
   xsol=[100.0 10.0 10.0] ;
   fit = zeros(11,1) ;
   for i = 1:11
     h =(2.0*(i-1.0)-xsol(3))/xsol(2) ;
     fit(i)=xsol(1)*exp(-h*h/2.0)+sin(10.0*i)*1.0e-2 ;
   end
   options = [] ;
  
%     End of problem definition Artificial problem
  

