home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21fb.zip / octave / SCRIPTS.ZIP / scripts.fat / polynom / polyfit.m < prev    next >
Text File  |  1999-12-24  |  2KB  |  84 lines

  1. ## Copyright (C) 1996, 1997 John W. Eaton
  2. ##
  3. ## This file is part of Octave.
  4. ##
  5. ## Octave is free software; you can redistribute it and/or modify it
  6. ## under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## Octave is distributed in the hope that it will be useful, but
  11. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. ## General Public License for more details.
  14. ##
  15. ## You should have received a copy of the GNU General Public License
  16. ## along with Octave; see the file COPYING.  If not, write to the Free
  17. ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  18. ## 02111-1307, USA.
  19.  
  20. ## -*- texinfo -*-
  21. ## @deftypefn {Function File} {[@var{p}, @var{yf}] =} polyfit (@var{x}, @var{y}, @var{n})
  22. ## Return the coefficients of a polynom @var{p}(@var{x}) of degree
  23. ## @var{n} that minimizes 
  24. ## @iftex
  25. ## @tex
  26. ## $$
  27. ## \sum_{i=1}^N (p(x_i) - y_i)^2
  28. ## $$
  29. ## @end tex
  30. ## @end iftex
  31. ## @ifinfo
  32. ## @code{sumsq (p(x(i)) - y(i))},
  33. ## @end ifinfo
  34. ##  to best fit the data in the least squares sense.
  35. ## 
  36. ## If two output arguments are requested, the second contains the values of
  37. ## the polynom for each value of @var{x}.
  38. ## @end deftypefn
  39.  
  40. ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
  41. ## Created: 13 December 1994
  42. ## Adapted-By: jwe
  43.  
  44. function [p, yf] = polyfit (x, y, n)
  45.  
  46.  
  47.   if (nargin != 3)
  48.     usage ("polyfit (x, y, n)");
  49.   endif
  50.  
  51.   if (! (is_vec (x) && is_vec (y) && size (x) == size (y)))
  52.     error ("polyfit: x and y must be vectors of the same size");
  53.   endif
  54.  
  55.   if (! (is_scal (n) && n >= 0 && ! isinf (n) && n == round (n)))
  56.     error ("polyfit: n must be a nonnegative integer");
  57.   endif
  58.  
  59.   y_is_row_vector = (rows (y) == 1);
  60.  
  61.   l = length (x);
  62.   x = reshape (x, l, 1);
  63.   y = reshape (y, l, 1);
  64.  
  65.   X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n));
  66.  
  67.   p = X \ y;
  68.  
  69.   if (nargout == 2)
  70.     yf = X * p;
  71.  
  72.     if (y_is_row_vector)
  73.       yf = yf.';
  74.     endif
  75.   endif
  76.  
  77.   p = flipud (p);
  78.  
  79.   if (! prefer_column_vectors)
  80.     p = p.';
  81.   endif
  82.  
  83. endfunction
  84.