Advertisement
Guest User

Untitled

a guest
May 28th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. function [p, s, mu] = polyfit (x, y, n)
  2.  
  3. if (nargin < 3 || nargin > 4)
  4. print_usage ();
  5. endif
  6.  
  7. if (nargout > 2)
  8. ## Normalized the x values.
  9. mu = [mean(x), std(x)];
  10. x = (x - mu(1)) / mu(2);
  11. endif
  12.  
  13. if (! size_equal (x, y))
  14. error ("polyfit: x and y must be vectors of the same size");
  15. endif
  16.  
  17. if (! (isscalar (n) && n >= 0 && ! isinf (n) && n == round (n)))
  18. error ("polyfit: n must be a nonnegative integer");
  19. endif
  20.  
  21. y_is_row_vector = (rows (y) == 1);
  22.  
  23. ## Reshape x & y into column vectors.
  24. l = numel (x);
  25. x = x(:);
  26. y = y(:);
  27.  
  28. ## Construct the Vandermonde matrix.
  29. v = vander (x, n+1);
  30.  
  31. ## Solve by QR decomposition.
  32. [q, r, k] = qr (v, 0);
  33. p = r \ (q' * y);
  34. p(k) = p;
  35.  
  36. if (nargout > 1)
  37. yf = v*p;
  38.  
  39. if (y_is_row_vector)
  40. s.yf = yf.';
  41. else
  42. s.yf = yf;
  43. endif
  44.  
  45. s.R = r;
  46. s.X = v;
  47. s.df = l - n - 1;
  48. s.normr = norm (yf - y);
  49. endif
  50.  
  51. ## Return a row vector.
  52. p = p.';
  53.  
  54. endfunction
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement