function [betaHat, aHat] = olsEstimates(X, y); % olsEstimates Estimates parameters for OLS. % % Parameters for a multiple regression are estimated by using OLS. % All variables (dependent and independent) are standardized % and estimates for standardized and original units are calculated. % % USE: % [betaHat, aHat] = olsEstimates(X, y) % % betaHat = Estimates in standardized unit, % aHat = Estimtes in the original unit. % % X = independent variable (include a column of ones for intercept) % y = dependent variable. % Tomo Eguchi % 28 January 2002 %X1 = normrnd(4,3,30,1); X2=normrnd(5,20,30,1);X3=normrnd(12,3,30,1);X4=normrnd(0,3,30,1); %X = [ones(30, 1), X1, X2, X3, X4]; %X1 = [ones(30, 1), X]; %trueA = [4; 3; 12; 9; 5]; %y = X*trueA + normrnd(0, 1, 30, 1); [sampleSz, nPars] = size(X); % find the dimension of data matrix Int = 0; % initialize the intercept term if (sum(X(:, 1)) == sampleSz), % if the first column of the data matrix X = X(:, 2:end); % sums to the sample size, then there is an Int = 1; % intercept term. end corX = cor(X); % compute correlation matrix of X corXy = cor(X, y); % compute correlation vector between X and y betaHat = inv(corX) * corXy'; % estimate parameters in standardized unit sdY = std(y); % compute standard deviations of X and y sdX = std(X); aHat = ((sdY./sdX) .* betaHat')'; % compute back into the original unit. if Int == 1, % if there is an intercept, compute that too. a0 = mean(y) - mean(X) * aHat; aHat = [a0; aHat]; end