% LMcs110302_4th.m
% Hypothesis testing with general linear model
% Larsen & Marx Case Study 11.3.2
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th edition
% Written by Eugene.Gallagher@umb.edu; written 11/23/10; revised 11/23/10
DATA=...
[1765 407;1942 466;2132 489;2431 545;2642 610;2895 659;2931 686;3217 724];
[r,c]=size(DATA);df=r-2;
 X=[ones(r,1) DATA(:,1)];Y=DATA(:,2);
B=X\Y;
fprintf('\nThe Y intercept = %8.3f and slope = %5.3f\n',B(1),B(2));
Yest=X*B;
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);
% Now use Matlab's regress to produce the same regression coefficients:
[b,bint,r,rint,stats] = regress(Y,X);
% Note for other problems, more significant figures will be needed for
% reporting the regression coefficients and 95%% CI's
fprintf('\nThe Y intercept = %2.0f with 95%% CI = [%2.0f %2.0f]\n',...
    b(1),bint(1,1),bint(1,2));
fprintf('The slope is %4.2f with 95%% CI = [%4.2f %4.2f]\n',...
    b(2),bint(2,1),bint(2,2));
fprintf(...
'R^2 = %4.1f%%; F = %5.1f with p-value = %7.2g; RMSE = s^2 = %4.1f\n',...
    stats(1)*100,stats(2),stats(3),stats(4))
P=2*(1-tcdf(sqrt(stats(2)),df));
fprintf('P(t >= %4.1f |Ho: slope = 0 & %3.0f df) = %7.2g\n',...
    sqrt(stats(2)),df,P)
s=sprintf('Expenses = %2.0f +/- %2.0f + %4.2f +/- %4.2f * Sales',...
    b(1),bint(1,2)-b(1),b(2),bint(2,2)-b(2));
plot(X(:,2),Y,'o',Xs,Ys,'m','LineWidth',2,...
                       'MarkerEdgeColor','k',...
                       'MarkerFaceColor','b',...
                       'MarkerSize',8)
axis([1600 3400 340 760]);
ax1=gca;
xlabel('Sales','Color','black','FontSize',20)
ylabel('Expenses','Color','black','FontSize',20)
text(2100,450,s,'FontSize',16)
 set(ax1,'xtick',2000:500:3000,'FontSize',16)
 set(ax1,'xticklabel',{'$2000', '$2500','$3000'},'FontSize',16)
 set(ax1,'ytick',350:100:750,'FontSize',16)
  set(ax1,'yticklabel',{'$350', '$450','$550','$650','$750'},...
      'FontSize',16)
  title('Figure 11.3.3','FontSize',22)
figure(gcf)
pause
hold off
plot(Yest,Resid,'ok');
xlabel('Expected value','FontSize',20),ylabel('Residual','FontSize',20);
grid;figure(gcf)