2261
|
1 function p = polyfit (x, y, n) |
|
2 |
|
3 # usage: polyfit (x, y, n) |
|
4 # |
|
5 # Returns the coefficients of a polynomial p(x) of degree n that |
|
6 # minimizes sumsq (p(x(i)) - y(i)), i.e., that best fits the data |
|
7 # in the least squares sense. |
|
8 |
|
9 # Written by KH (Kurt.Hornik@ci.tuwien.ac.at) on Dec 13, 1994 |
|
10 # Copyright Dept of Statistics and Probability Theory TU Wien |
|
11 |
|
12 if (nargin != 3) |
|
13 usage ("polyfit (x, y, n)"); |
|
14 endif |
|
15 |
|
16 if (! (is_vector (x) && is_vector (y) && size (x) == size (y))) |
|
17 error ("polyfit: x and y must be vectors of the same size"); |
|
18 endif |
|
19 |
|
20 if (! (is_scalar (n) && n >= 0 && ! isinf (n) && n == round (n))) |
|
21 error ("polyfit: n must be a nonnegative integer"); |
|
22 endif |
|
23 |
|
24 l = length (x); |
|
25 x = reshape (x, l, 1); |
|
26 y = reshape (y, l, 1); |
|
27 |
|
28 X = ones (l, 1); |
|
29 |
|
30 if (n > 0) |
|
31 tmp = (x * ones (1, n)) .^ (ones (l, 1) * (1 : n)); |
|
32 X = [X, tmp]; |
|
33 endif |
|
34 |
|
35 # Compute polynomial coeffients, making returned value compatible |
|
36 # with Matlab. |
|
37 |
|
38 [Q, R] = qr (X, 0); |
|
39 |
|
40 p = flipud (R \ (Q' * y)); |
|
41 |
|
42 if (! prefer_column_vectors) |
|
43 p = p'; |
|
44 endif |
|
45 |
|
46 endfunction |