x

6

4

1

0

3

5

8

y

18

13

6

4

1

8

15

% A function defined for least square regression
function [c,R2] =
linearregression(x,y)
% Leastsquares fit of data to y = c(1)*x + c(2)
% Here, c(1) = m; c(2) = b;
% Inputs:
% x,y = Vectors of independent and dependent variables
% Outputs:
% c = Coefficients of the given equation
if length(y)~= length(x)
error("x and y are not compatible");
end
% Least squares algorithm implementation
x = x(:); y = y(:); % x and y
are column vectors
A = [x ones(size(x))]; % mbyn
matrix of the system
c = (A'*A)\(A'*y); % Solving
normal equations
if nargout>1 % Checking number of function outputs
r = y  A*c;
R2 = 1  (norm(r)/norm(ymean(y)))^2;
end
Program Output:
>> x = [6 4 1 0 3 5 8];
>> y = [18 13 6 4 1 8 15];
>> linearregression(x,y)
ans =
2.3140
4.0814
No comments:
Post a Comment