home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21eb.zip / octave / SCRIPTS.ZIP / scripts.fat / polynom / polyfit.m < prev    next >
Text File  |  1999-04-29  |  2KB  |  73 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. ## usage:  [p, yf] = polyfit (x, y, n)
  21. ##
  22. ## Returns the coefficients of a polynom p(x) of degree n that
  23. ## minimizes sumsq (p(x(i)) - y(i)), i.e., that best fits the data
  24. ## in the least squares sense.
  25. ##
  26. ## If two outputs are requested, also return the values of the
  27. ## polynom for each value of x.
  28.  
  29. ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
  30. ## Created: 13 December 1994
  31. ## Adapted-By: jwe
  32.  
  33. function [p, yf] = polyfit (x, y, n)
  34.  
  35.  
  36.   if (nargin != 3)
  37.     usage ("polyfit (x, y, n)");
  38.   endif
  39.  
  40.   if (! (is_vec (x) && is_vec (y) && size (x) == size (y)))
  41.     error ("polyfit: x and y must be vectors of the same size");
  42.   endif
  43.  
  44.   if (! (is_scal (n) && n >= 0 && ! isinf (n) && n == round (n)))
  45.     error ("polyfit: n must be a nonnegative integer");
  46.   endif
  47.  
  48.   y_is_row_vector = (rows (y) == 1);
  49.  
  50.   l = length (x);
  51.   x = reshape (x, l, 1);
  52.   y = reshape (y, l, 1);
  53.  
  54.   X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n));
  55.  
  56.   p = X \ y;
  57.  
  58.   if (nargout == 2)
  59.     yf = X * p;
  60.  
  61.     if (y_is_row_vector)
  62.       yf = yf';
  63.     endif
  64.   endif
  65.  
  66.   p = flipud (p);
  67.  
  68.   if (! prefer_column_vectors)
  69.     p = p.';
  70.   endif
  71.  
  72. endfunction
  73.