% M-file to
%    - compute equation for least squares regression line
%    - plot least squares regression line on a graph with the data
%    - compute the correlation coefficient
%    - compute the coefficient of determination
% LSR = least square regression

% Enter the data
x = [2 5 2 4 6];
y = [4 7 5 8 11];

% Find the equation for the LSR line
C = polyfit(x,y,1);
% Display the equation
fprintf('Eqn for LSR: yhat = %f x + %f\n',C(1),C(2))

% Find the yhat value for each x value
yhat = polyval(C,x);

% Plot the data and the LSR line
plot(x,y,'k.',x,yhat,'k-')
xlabel('x')
ylabel('y')
xlim([min(x)-1 max(x)+1]) %Set x-axis a little wider than data

% Find the correlation coefficient
rho = corrcoef(x,y);
% Display the correlation coefficient
fprintf('rho = %f\n',rho(1,2))
% Display the coefficient of determination
fprintf('The regression line accounts for %5.2f%% ',rho(1,2)*100)
fprintf('of the variance in the data\n')
