Develop a function that will calculate slope m and intercept
Develop a function that will calculate slope m and intercept b of the least-squares line that best fits an input data set. The input data points (x,y) will be passed tothe function in two input arrays, x and y. Test your function using a test program and the following 20-point data set:
x = [-4.91 -3.84 -2.41 -2.62 -3.78 -0.52 -1.83 -2.01 0.28 1.08 -0.94 0.59 0.69 3.04 1.01 3.60 4.53 5.13 4.43 4.12 ];
y = [-8.18 -7.49 -7.11 -6.15 -5.62 -3.30 -2.05 -2.83 -1.16 0.52 0.21 1.73 3.96 4.26 5.75 6.67 7.70 7.31 9.05 10.95 ];
Solution
Writting code in matlab language :
%Given observations array x and y
%Let line that best fit them be y = mx + c
%We know that, by minimizing square error of distance from line
% m = [ summation over all i (yi - average(y))*(xi - average(x)) ] divided
% by [ summation over all i (xi- average(x))^2 ]
% c = average(y) - m*average(x)
function [ slope, intercept ] = fitLine( X, Y )
average_x = sum(X,2);
average_y = sum(Y,2);
slopeNum = 0.0;
slopeDen = 0.0;
for i=1:size(X,1)
slopeNum = slopeNum + (Y(i,1)- average_y)*(X(i,1)- average_x);
slopeDen = slopeDen + (X(i,1)- average_x)*(X(i,1)- average_x);
end
slope = (slopeNum*1.0)/slopeDen;
intercept = average_y - slope*average_x;
end
