2313
|
1 ## Copyright (C) 1996 John W. Eaton |
|
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 |
2311
|
20 ## usage: polyfit (x, y, n) |
|
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. |
|
25 |
2312
|
26 ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at> |
|
27 ## Created: 13 December 1994 |
|
28 ## Adapted-By: jwe |
|
29 |
2261
|
30 function p = polyfit (x, y, n) |
2325
|
31 |
|
32 |
2261
|
33 if (nargin != 3) |
|
34 usage ("polyfit (x, y, n)"); |
|
35 endif |
2325
|
36 |
2261
|
37 if (! (is_vector (x) && is_vector (y) && size (x) == size (y))) |
|
38 error ("polyfit: x and y must be vectors of the same size"); |
|
39 endif |
2325
|
40 |
2261
|
41 if (! (is_scalar (n) && n >= 0 && ! isinf (n) && n == round (n))) |
|
42 error ("polyfit: n must be a nonnegative integer"); |
|
43 endif |
2325
|
44 |
2261
|
45 l = length (x); |
|
46 x = reshape (x, l, 1); |
|
47 y = reshape (y, l, 1); |
2325
|
48 |
2261
|
49 X = ones (l, 1); |
|
50 |
|
51 if (n > 0) |
|
52 tmp = (x * ones (1, n)) .^ (ones (l, 1) * (1 : n)); |
|
53 X = [X, tmp]; |
|
54 endif |
|
55 |
2303
|
56 ## Compute polynomial coeffients, making returned value compatible |
|
57 ## with Matlab. |
2261
|
58 |
|
59 [Q, R] = qr (X, 0); |
|
60 |
|
61 p = flipud (R \ (Q' * y)); |
|
62 |
|
63 if (! prefer_column_vectors) |
|
64 p = p'; |
|
65 endif |
|
66 |
|
67 endfunction |