This program fits a straight line to a
given set of coordinates using
the method of least
squares ( linear regression ).
||The coefficients of
of determination, coefficient
of correlation and standard
error of estimate are calculated. Once the line has been
fitted, you may predict values of y
for given values of x.
We develop the following Matlab code (note that Matlab has its own
built-in functions to make linear
easier for all of us, but we'd like to
show a step-by-step way to do it, to understand the inner concepts):
[y0, a, b, r2, r, k2] = lin_reg(x, y, x0)
j = 0; k
= 0; l = 0; m = 0; r2 = 0;
(n*r2 - k*j)/(n*l - j^2);
a = (k -
b*(r2 - j*k/n);
m = m -
k = m -
r2 = j/m;
y0 = a +
If we have the following data available (where every yi has its correspondent xi):
x = [71
73 64 65 61
70 65 72 63 67 64];
y = [160
183 154 168 159 180 145 210 132 168 141];
we can call the function above in this manner (to obtain interpolated
values for x = 70 and x = 72):
b, r2, r, k2] = lin_reg(x, y, 70)
lin_reg(x, y, 72)
And the Matlab response is:
r2 = 0.5563
k2 = 15.4135
y0 = 184.6083
We can use the 'polyfit'
instructions in Matlab for this purpose, like this:
polyfit(x, y, 1)
a straight line through the data means thet we want to find the
polynomial coefficients of a first order polynomial such that a1xi
gives the best approximation for yi.
We find the coefficients with 'polyfit'
and evaluate any xi
The Matlab results is
confirming our previous numbers.
'Linear Regression' to 'Matlab Cookbook'