3092
|
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 |
3091
|
48 y_is_row_vector = (rows (y) == 1); |
|
49 |
2261
|
50 l = length (x); |
|
51 x = reshape (x, l, 1); |
|
52 y = reshape (y, l, 1); |
2325
|
53 |
3061
|
54 ## Unfortunately, the economy QR factorization doesn't really save |
|
55 ## memory doing the computation -- the returned values are just |
|
56 ## smaller. |
2261
|
57 |
3061
|
58 ## [Q, R] = qr (X, 0); |
|
59 ## p = flipud (R \ (Q' * y)); |
2261
|
60 |
3061
|
61 ## XXX FIXME XXX -- this is probably not so good for extreme values of |
|
62 ## N or X... |
2261
|
63 |
3061
|
64 X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n)); |
2261
|
65 |
3091
|
66 p = (X' * X) \ (X' * y); |
|
67 |
|
68 if (nargout == 2) |
|
69 yf = X * p; |
|
70 endif |
|
71 |
|
72 p = flipud (p); |
2261
|
73 |
|
74 if (! prefer_column_vectors) |
|
75 p = p'; |
|
76 endif |
|
77 |
3091
|
78 if (y_is_row_vector) |
|
79 yf = yf'; |
3061
|
80 endif |
|
81 |
2261
|
82 endfunction |