Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [p, s, mu] = polyfit (x, y, n)
- if (nargin < 3 || nargin > 4)
- print_usage ();
- endif
- if (nargout > 2)
- ## Normalized the x values.
- mu = [mean(x), std(x)];
- x = (x - mu(1)) / mu(2);
- endif
- if (! size_equal (x, y))
- error ("polyfit: x and y must be vectors of the same size");
- endif
- if (! (isscalar (n) && n >= 0 && ! isinf (n) && n == round (n)))
- error ("polyfit: n must be a nonnegative integer");
- endif
- y_is_row_vector = (rows (y) == 1);
- ## Reshape x & y into column vectors.
- l = numel (x);
- x = x(:);
- y = y(:);
- ## Construct the Vandermonde matrix.
- v = vander (x, n+1);
- ## Solve by QR decomposition.
- [q, r, k] = qr (v, 0);
- p = r \ (q' * y);
- p(k) = p;
- if (nargout > 1)
- yf = v*p;
- if (y_is_row_vector)
- s.yf = yf.';
- else
- s.yf = yf;
- endif
- s.R = r;
- s.X = v;
- s.df = l - n - 1;
- s.normr = norm (yf - y);
- endif
- ## Return a row vector.
- p = p.';
- endfunction
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement