function [b, ts, r2]=ols_reg(y,x,c) %OLSH(X, Y) runs a linear regression of the vector y on % the matrix x and reports the results. %c=1 includes the constant [t, k] = size(x); % t = # of obs., k = # of regressors [m, n] = size(y); if n > 1 error('y must be a vector.'); end if m ~= t error('y and x must have the same number of rows.'); end if k > t error('More parameters than observations.'); end df = t - k; % degrees of freedom if c== 1 x= [ones(t,1) x]; else x=x; end %--- compute the moment matrix, coefficient vector and residuals ---% b = inv(x'*x)*x'*y; % coefficients u = y - x*b; % residuals tss = (t-1) * std(y)^2; % total sum of squares rss = u'*u; % residual sum of squares ess = tss - rss; % explained sum of squares %--- compute the variance/covariance matrix of b ---% vc = rss * inv(x'*x) / df; %--- compute various regression statistics ---% se = sqrt(diag(vc)); % standard errors of b ts = b ./ se; % t statistics r2 = ess / tss; % R-squared dw = sum( (u(2:t) - u(1:t-1)).^2 )' / rss; % Durbin-Watson statistic