function fitnlm_test ( )

%*****************************************************************************80
%
%% fitnlm_test tests the nonlinear least squares fitting function fitnlm.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2019
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'fitnlm_test\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test fitnlm, a function which carries out\n' );
  fprintf ( 1, '  nonlinear regression, creating a model y = modelfun ( a, x )\n' );
  fprintf ( 1, '  using (x,y) data supplied by the user,\n' );
  fprintf ( 1, '  and a model function with unknown coefficients a\n' );
%
%  Read data from file and split into x and y vectors.
%
  data = load ( 'nmr.txt' );
  x = data(:,1);
  y = data(:,2);
%
%  Set an initial estimate for the unknown coefficients.
%
  a0 = [ 1.0, 25.0 ];
%
%  Call fitnlm() to get a model.
%
  model = fitnlm ( x, y, @modelfun, a0 )
%
%  We can extract the coefficients from the model this way.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Coefficient vector a:\n' );

  a = model.Coefficients{:,1}
%
%  We can evaluate the model at the data points this way:
%
  yfit = feval ( model, x );
%
%  ...OR use the coefficients that we extracted, and our modelfun function.
%
  yfit2 = modelfun ( a, x );
%
%  Plot the data and the model.
%
  plot ( x, y, 'bo', x, yfit, 'r-' );
  grid ( 'on' );
  title ( 'Y = A(1) * exp ( - A(2) * X' );
  print ( '-dpng', 'fitnlm_test.png' );
%
%  Tabulate the data and the model.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  X  Y  Yfit(A,X)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : length ( x )
    fprintf ( 1, '  %f  %f  %f\n', x(i), y(i), yfit(i) );
  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FITNLM_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function y = modelfun ( a, x )

%*****************************************************************************80
%
%% modelfun expresses the model whose coefficients we are seeking.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2019
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A(K), a set of parameter values.
%
%    Input, real X(N), a set of X data.
%
%    Output, real Y(N), the model function, using the given parameters,
%    evaluated at the X data.
%
  y = a(1) * exp ( - a(2) * x );

  return
end
