%   Least-squares Linear fit for two 
%   time series x and y
%   of the form : y = mx + c
%   Author: Santhanam, Balu
%   Date  : 02/27/99
%   SYNOPSIS:
%   [m,c] = lslinfit(x,y)
%   m   : least-quares estimate of the slope of linear fit 
%   c   : least-squares estimate of the y intercept 
%****************************************************************************** 
function [m,c] = lslinfit(x,y)
%
%*************************
%  Initial Error check
%*************************
if nargin ~= 2 
   error('Insufficient Information')
elseif length(x) == 0 | length(y) == 0 
   error('Null input')
elseif length(x) ~= length(y)
   error('x and y need to be of the same size')
elseif isnumeric(x) == 0 | isnumeric(y) == 0
   error('Non-numeric Characters in the input')
elseif all(isfinite(x)) == 0 |  all(isfinite(y)) == 0
   error('Nan or Inf Values in the Input')
elseif any(y) == 0
   m = 0; c = 0; 
end
%
%***************************************************************
%  Least-squares Inversion of the Over Determined 
%  System Ax = b
%***************************************************************
x = x(:); y = y(:); % Convert both time series to column vectors
A = [x , ones(size(x))]; b = y;
if rank(A) == 2
   x_ls = A\b; 
   m = x_ls(1); c = x_ls(2);
else 
   x_ls = pinv(A)*b;
    m = x_ls(1);  c = x_ls(2);
end
%**************************************************************

