1 ## Copyright (C) 2007 Andreas Stahel <Andreas.Stahel@bfh.ch>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
16 ## general linear regression
18 ## [p,y_var,r,p_var]=LinearRegression(F,y)
19 ## [p,y_var,r,p_var]=LinearRegression(F,y,weight)
21 ## determine the parameters p_j (j=1,2,...,m) such that the function
22 ## f(x) = sum_(i=1,...,m) p_j*f_j(x) fits as good as possible to the
23 ## given values y_i = f(x_i)
26 ## F n*m matrix with the values of the basis functions at the support points
27 ## in column j give the values of f_j at the points x_i (i=1,2,...,n)
28 ## y n column vector of given values
29 ## weight n column vector of given weights
32 ## p m vector with the estimated values of the parameters
33 ## y_var estimated variance of the error
34 ## r weighted norm of residual
35 ## p_var estimated variance of the parameters p_j
37 function [p,y_var,r,p_var]=LinearRegression(F,y,weight)
39 if (nargin < 2 || nargin >= 4)
40 usage('wrong number of arguments in [p,y_var,r,p_var]=LinearRegression(F,y)');
43 [rF, cF] = size(F); [ry, cy] =size(y);
44 if (rF ~= ry || cy > 1)
45 error ('LinearRegression: incorrect matrix dimensions');
48 if (nargin==2) % set uniform weights if not provided
55 wF(:,j)=weight.*F(:,j);
58 [Q,R]=qr(wF,0); % estimate the values of the parameters
62 residual=F*p-y; % compute the residual vector
63 r=norm(weight.*residual); % and its weighted norm
64 % variance of the weighted y-errors
65 y_var= sum((residual.^2).*(weight.^4))/(rF-cF);
67 if nargout>3 % compute variance of parameters only if needed
68 %% M=inv(R)*Q'*diag(weight);
71 M(j,:)=M(j,:).*(weight');
73 M=M.*M; % square each entry in the matrix M
74 p_var=M*(y_var./(weight.^4)); % variance of the parameters