Thursday, August 5, 2021

Linear Least-Squares Regression

Here is an M-file to implement linear regression. 

Linear Regression M-file

function [a,r2,syx] = linregr(x,y)
% linregr: linear regression curve fitting
%   [a, r2] = linregr(x,y): Least squares fit of straight line to data by solving the normal equations
% input:
%   x = independent variable
%   y = dependent variable
% output:
%   a = vector of slope, a(1), and intercept, a(2)
%   r2 = coefficient of determination
%   syx = standard error of estimate

n = length(x); % show number of data
if length(y)~=n, error('x and y must be same length'); end
% error checking to have complete number of data points
x = x(:); y = y(:); % convert to column vectors
sx = sum(x); sy = sum(y);
sx2 = sum(x.*x); sxy = sum(x.*y); sy2 = sum(y.*y);
a(1) = (n*sxy-sx*sy)/(n*sx2-sx^2); % a(1) = slope
a(2) = sy/n-a(1)*sx/n; % a(2) = intercept
r2 = ((n*sxy-sx*sy)/sqrt(n*sx2-sx^2)/sqrt(n*sy2-sy^2))^2;
Sr = sum((y-a(2)-a(1)*x).^2);
St = sum((y-mean(y)).^2);
syx = sqrt(Sr/(n-2)); 

% create plot of data and best fit line
xp = linspace(min(x),max(x),2);
yp = a(1)*xp+a(2);
% best fit line equation
plot(x,y,'o',xp,yp),xlabel('x'),ylabel('y')
% to generate plot of x vs y with circle marker and plot for best fit line
grid on

No comments:

Post a Comment

Numerical Integration Formulas

Here are the M-files to implement composite trapezoidal rule for equally spaced data and unequally spaced data.  Composite Trapezoidal Rule ...