2847
|
1 ## Copyright (C) 1996, 1997 John W. Eaton |
2313
|
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. |
2303
|
19 |
3061
|
20 ## usage: [p, yf] = polyfit (x, y, n) |
2311
|
21 ## |
|
22 ## Returns the coefficients of a polynomial p(x) of degree n that |
2325
|
23 ## minimizes sumsq (p(x(i)) - y(i)), i.e., that best fits the data |
2311
|
24 ## in the least squares sense. |
3061
|
25 ## |
|
26 ## If two outputs are requested, also return the values of the |
|
27 ## polynomial for each value of x. |
2311
|
28 |
2312
|
29 ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at> |
|
30 ## Created: 13 December 1994 |
|
31 ## Adapted-By: jwe |
|
32 |
3061
|
33 function [p, yf] = polyfit (x, y, n) |
2325
|
34 |
|
35 |
2261
|
36 if (nargin != 3) |
|
37 usage ("polyfit (x, y, n)"); |
|
38 endif |
2325
|
39 |
2261
|
40 if (! (is_vector (x) && is_vector (y) && size (x) == size (y))) |
|
41 error ("polyfit: x and y must be vectors of the same size"); |
|
42 endif |
2325
|
43 |
2261
|
44 if (! (is_scalar (n) && n >= 0 && ! isinf (n) && n == round (n))) |
|
45 error ("polyfit: n must be a nonnegative integer"); |
|
46 endif |
2325
|
47 |
2261
|
48 l = length (x); |
|
49 x = reshape (x, l, 1); |
|
50 y = reshape (y, l, 1); |
2325
|
51 |
3061
|
52 ## Unfortunately, the economy QR factorization doesn't really save |
|
53 ## memory doing the computation -- the returned values are just |
|
54 ## smaller. |
2261
|
55 |
3061
|
56 ## [Q, R] = qr (X, 0); |
|
57 ## p = flipud (R \ (Q' * y)); |
2261
|
58 |
3061
|
59 ## XXX FIXME XXX -- this is probably not so good for extreme values of |
|
60 ## N or X... |
2261
|
61 |
3061
|
62 X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n)); |
2261
|
63 |
3069
|
64 p = flipud ((X' * X) \ (X' * y)); |
2261
|
65 |
|
66 if (! prefer_column_vectors) |
|
67 p = p'; |
|
68 endif |
|
69 |
3061
|
70 if (nargout == 2) |
|
71 yf = X * p; |
|
72 endif |
|
73 |
2261
|
74 endfunction |