function p3_ex3 ( )

%*****************************************************************************80
%
%% p3_ex3, project 3, exercise 3.
%
%  Discussion:
%
%    Multilinear regression.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 March 2019
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'p3_ex3:\n' );
  fprintf ( 1, '  MATLAB version.\n' );
  fprintf ( 1, '  Linear regression for model parameters.\n' );
%
%  Read training data and copy into vectors.
%
  data_train = load ( 'insurance_train.txt' );

  age = data_train(:,1);
  sex = data_train(:,2);
  bmi = data_train(:,3);
  children = data_train(:,4);
  smoker = data_train(:,5);
  region = data_train(:,6);
  charges = data_train(:,7);

  num_train = length ( age );
%
%  Matrix A uses a column of 1's, then x.
%
  A = [ ones(num_train,1), age, sex, bmi, children, smoker ];
%
%  Seek [b,m] so that y=A*[b,m];
%
  x = A \ charges;
  rms_norm = rms ( A * x - charges );
%
%  Report solution and residual.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimate linear model parameters on training data:\n' );
  fprintf ( 1, '  Number of training records = %d\n', num_train );
  fprintf ( 1, '  RMS of training residual = %g\n', rms_norm );
  fprintf ( 1, '  Average charge           = %g\n', mean ( charges ) );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Seek relationship y = c1 * 1 + c2 * age + c3 * sex + c4 * bmi + c5 * children + c5 * smoker\n' );
  fprintf ( 1, '  c1 = %g\n', x(1) );
  fprintf ( 1, '  c2 = %g\n', x(2) );
  fprintf ( 1, '  c3 = %g\n', x(3) );
  fprintf ( 1, '  c4 = %g\n', x(4) );
  fprintf ( 1, '  c5 = %g\n', x(5) );
  fprintf ( 1, '  c6 = %g\n', x(6) );
%
%  Demonstrate some examples.
%  (Note that in some cases a NEGATIVE charge can be predicted!)
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Index  Predicted    Actual\n' );
  fprintf ( 1, '\n' );
  for j = 200 : 200 : 1000
    predicted = x(1) + x(2) * age(j) + x(3) * sex(j) + x(4) * bmi(j) + x(5) * children(j) + x(6) * smoker(j);
    fprintf ( 1, '   %4d   %8.2f  %8.2f\n', j, predicted, charges(j) );
  end
%
%  Read testing data and copy into vectors.
%
  data_test = load ( 'insurance_test.txt' );

  age = data_test(:,1);
  sex = data_test(:,2);
  bmi = data_test(:,3);
  children = data_test(:,4);
  smoker = data_test(:,5);
  region = data_test(:,6);
  charges = data_test(:,7);

  num_test = length ( age );

  A = [ ones(num_test,1), age, sex, bmi, children, smoker ];
  rms_norm = rms ( A * x - charges );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Evaluate model on testing data:\n' );
  fprintf ( 1, '  Number of testing records = %d\n', num_test );
  fprintf ( 1, '  RMS of testing residual = %g\n', rms_norm );
  fprintf ( 1, '  Average charge           = %g\n', mean ( charges ) );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'p3_ex3:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end
