function [ a, b ] = llsq ( n, x, y )

%*****************************************************************************80
%
%% llsq() solves a linear least squares problem, matching a line to data.
%
%  Discussion:
%
%    A formula for a line of the form Y = A * X + B is sought, which
%    will minimize the root-mean-square error to N data points ( X(I), Y(I) );
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    08 April 2018
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer N, the number of data values.
%
%    real X(N,1), Y(N,1), the coordinates of the data points.
%
%  Output:
%
%    real A, B, the slope and Y-intercept of the least-squares approximant
%    to the data.
%

%
%  Force data to be column vectors!
%
  x = x(:);
  y = y(:);
%
%  Special case.
%
  if ( n == 1 )
    a = 0.0;
    b = y(1);
    return
  end
%
%  Average X and Y.
%
  xbar = sum ( x(1:n) ) / n;
  ybar = sum ( y(1:n) ) / n;
%
%  Recenter X and Y around their average values.
%
  xb = x(1:n) - xbar;
  yb = y(1:n) - ybar;

  top = xb' * yb;
  bot = xb' * xb;
%
%  Compute A and B.
%
  a = top / bot;

  b = ybar - a * xbar;

  return
end
