% LMcs110201_4th.m
% Case Study 11.2.1, page 648-650
% Larsen & Marx (2006) Introduction to Mathematical Statistics. 4th Edition
% Written 10/2010 by Eugene.Gallagher@umb.edu 2001, revised 2/18/11
% http://alpha.es.umb.edu/faculty/edg/files/edgwebp.html
% Regression of finished weight of rods (y) vs. rough casting weight (x)
DATA=[2.745 2.08
    2.7 2.045
    2.69 2.05
    2.68 2.005
    2.675 2.035
    2.670 2.035
    2.665 2.02
    2.66 2.005
    2.655 2.01
    2.655 2.0
    2.65 2
    2.65 2.005
    2.645 2.015
    2.635 1.99
    2.630 1.99
    2.625 1.995
    2.625 1.985
    2.62 1.97
    2.615 1.985
    2.615 1.99
    2.615 1.995
    2.61 1.99
    2.59 1.975
    2.59 1.995
    2.565 1.955];
[r,c]=size(DATA);
% To fit the Y intercept in Matlab, need to have a column vector of 1's:
X=[ones(r,1) DATA(:,1)]
Y=DATA(:,2);
B=X\Y;
    fprintf('\nThe Y intercept = %5.3f and slope = %5.3f\n',B(1),B(2));
    Yest=X*B;
    s=sprintf('y = %5.3f + %5.3f x',B);  % this writes a string variable
    %                                      for plotting in the graph
    Resid=Y-Yest;
    % sort by the independent variable so the lines are smooth
    [Xs,k]=sort(X(:,2));
    % sort the estimated values using the index vector k:
    Ys=Yest(k);
    plot(DATA(:,1),DATA(:,2),'sg',Xs,Ys,'-r','LineWidth',2);
    xlabel('Rough Weight','FontSize',16),
    ylabel('Finished Weight','FontSize',16)
    text(2.5768,2.0309,s,'FontSize',16)
    title('Figure 11.2.1','FontSize',20)
    figure(gcf)
    pause
    % Not in text, but plot the residuals
    plot(X(:,2),Resid,'ok');
    xlabel('Rough Weight','FontSize',16)
    ylabel('Residuals','FontSize',16);
    title('Residuals for Figure 11.2.1','FontSize',20)
    figure(gcf)