%% Estimate White's Robust Covariance for OLS Coefficient Estimates
% Model an automobile's price with its curb weight, engine size, and cylinder bore diameter using the linear model:
% \texttt{price}_i = {\beta _0} + {\beta _1}\texttt{curbWeight}_i + {\beta _2}\texttt{engineSize}_i + {\beta _3}\texttt{bore}_i + {\varepsilon _i}.
% Estimate model coefficients and White's robust covariance.
% Load the 1985 automobile imports data set (Frank and Asuncion, 2012). Extract the columns that correspond to the predictor and response variables.

load imports-85
Tbl = table(X(:,7),X(:,8),X(:,9),X(:,15),...
   'Variablenames',{'curbWeight','engineSize',...
   'bore','price'});

%
% Fit the linear model to the data and plot the residuals versus the fitted values.

Mdl = fitlm(Tbl);
plotResiduals(Mdl,'fitted')

% The residuals seem to flare out, which indicates heteroscedasticity.
%
% Compare the coefficient covariance estimate from OLS and from using hac to calculate White's heteroscedasticity robust estimate.

[LSCov,LSSe,coeff] = hac(Mdl,'type','HC','weights',...
   'CLM','display','off');
    %Usual OLS estimates, also found in 
    %Mdl.CoefficientCovariance
LSCov
[WhiteCov,WhiteSe,coeff] = hac(Mdl,'type','HC','weights',...
   'HC0','display','off'); % White's estimates
WhiteCov

% The OLS coefficient covariance estimate is not equal to White's robust estimate because the latter accounts for the heteroscedasticity in the residuals.
% Copyright 2015 The MathWorks, Inc.