//-------------------------------------------------------------------//

//  Syntax: polyfit(x, y, n)

//  Description:

//  Polynomial curve fitting
//

//  polyfit(x,y,n) finds the coefficients of a polynomial
//	formed from the data in vector x of degree n that fits
//	the data in vector y in a least-squares sense.  
//  
//  polyfit returns the coefficients of the n-th order polynomial
//  (in decending powers of x).
//
//  See Also: poly, polyval, roots
//
//-------------------------------------------------------------------//

polyfit = function(x, y, n)
{
   local(x)
   
   x = x[:];
   m = x.nr;
   if (m != y.nr) {
      error("row dim. of 1st argument must match row dim. of 2nd argument");
   }
   a[;n+1] = ones(m,1);
   for (i in n:1:-1) {
      a[;i] = a[;i+1].*x;
   }
   return a\y;
};
