2303
|
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. |
|
19 |
2311
|
20 ## usage: polyfit (x, y, n) |
|
21 ## |
|
22 ## Returns the coefficients of a polynomial p(x) of degree n that |
|
23 ## minimizes sumsq (p(x(i)) - y(i)), i.e., that best fits the data |
|
24 ## in the least squares sense. |
|
25 |
2261
|
26 function p = polyfit (x, y, n) |
|
27 |
2303
|
28 ## Written by KH (Kurt.Hornik@ci.tuwien.ac.at) on Dec 13, 1994 |
|
29 ## Copyright Dept of Statistics and Probability Theory TU Wien |
2261
|
30 |
|
31 if (nargin != 3) |
|
32 usage ("polyfit (x, y, n)"); |
|
33 endif |
|
34 |
|
35 if (! (is_vector (x) && is_vector (y) && size (x) == size (y))) |
|
36 error ("polyfit: x and y must be vectors of the same size"); |
|
37 endif |
|
38 |
|
39 if (! (is_scalar (n) && n >= 0 && ! isinf (n) && n == round (n))) |
|
40 error ("polyfit: n must be a nonnegative integer"); |
|
41 endif |
|
42 |
|
43 l = length (x); |
|
44 x = reshape (x, l, 1); |
|
45 y = reshape (y, l, 1); |
|
46 |
|
47 X = ones (l, 1); |
|
48 |
|
49 if (n > 0) |
|
50 tmp = (x * ones (1, n)) .^ (ones (l, 1) * (1 : n)); |
|
51 X = [X, tmp]; |
|
52 endif |
|
53 |
2303
|
54 ## Compute polynomial coeffients, making returned value compatible |
|
55 ## with Matlab. |
2261
|
56 |
|
57 [Q, R] = qr (X, 0); |
|
58 |
|
59 p = flipud (R \ (Q' * y)); |
|
60 |
|
61 if (! prefer_column_vectors) |
|
62 p = p'; |
|
63 endif |
|
64 |
|
65 endfunction |