function result = regres(y,x,intercept);
% 185C regression function
% USAGE result = regres(y,x,intercept)
% INPUTS:
%   y:          vector of dependent variables
%   x:          matrix of independent variables
%   intercept:  if intercept = 'n', no intercept will be added
%               default = 'y'
% OUTPUT:
%   result          structure of results
%   result.b        estimated coefficients
%   result.yhat     estimated dependent variable
%   result.resid    estimated residuals
%   result.R2       R Squared
%   result.se       Standard Error of estimated coefficients
%   result.CI95     95% confidence interval for coefficients.


[y,x] = check(y,x);  % Check that all parameters are proper

[n,k] = size(x);
result.b = (x'*x)^-1*x'*y; % Here is the regression
result.yhat = x*result.b;
result.resid = y - result.yhat;

RSS = result.resid'*result.resid;
varyhat = RSS/(n-k);
TSS = (y-mean(y))'*(y-mean(y));
result.R2 = 1 - (RSS/TSS);
A = (x'*x)^-1;
a = diag(A);
result.se = (varyhat * a).^.5;
tstat = result.b ./ result.se;
result.CI95 = [result.b - tinv(.975,n-k)*result.se, result.b + tinv(.975,n-k)*result.se];




function [y,x] = check(y,x)
[ny,ky] = size(y);
if (ny==1) & (ky == 1), error('Must have more than one observation for regression'); end;
if (ny~=1) & (ky ~= 1), error('Dependent variable must be vector'); end;
if ny == 1; y = y'; end; %Arrange y as col vector
[ny,ky] = size(y);
[nx,kx] = size(x);
if nx ==1 & kx == 1, error('Must have more than one observation for regression'); end;
if (nx ~= ny) & (kx ~= ny); error('Dependent and independent variables must have same number of observations'); end;
if nx ~= ny; x = x'; end; %Arrange x as y is arranged
n = length(y);
if nargin ==3
    if strcomp(intercept,'y') == 1; intercept = [];
    else intercept = ones(n,1);
    end;
else intercept = ones(n,1);
end;
[n,k] = size(x);

x = [intercept x];