Newey West Standard Error
12 views (last 30 days)
Show older comments
Please see below my Newey West Standard Error. Somehow its not working as intendet but i have no clue why. The error message of Matlab does not really contain helpful advise.
Can anyone of you identify the error that i made in the Code?
The file should get X and g (145) from my main file. It always says that it might be unbalanced but i dont see any unbalanced term.
function HCsterr = HCse(resid,X,const)
[n,~] = size(X);
if const == 1
X = [ones(n,1),X];
end
g = floor(4*(n/100)^(2/9));
R = sum( arrayfun( @(h) sum(X(h+1:n).*e(h+1:n).*e(1:n-h).*Xprime(1:n-h) + X(1:n-h).*e(1:n-h).e(h+1:n).*Xprime(h+1:n)) / (1 + h/(g+1), 1:g) ));
VCV = (X' * X)^(-1) * ((X' * diag(resid.^2) * X)+R) * (X' * X)^(-1);
% HCSE
HCsterr = sqrt(diag(VCV));
end
%
0 Comments
Accepted Answer
Steven Lord
on 30 Nov 2015
I think you have a closing parenthesis in the wrong place. Look at the last piece of your longest line:
(1 + h/(g+1), 1:g) ));
Look at this piece of that expression. It is enclosed in parentheses (two opening parentheses are matched by two closing parentheses) but it has a comma in the middle. Usually that pattern occurs when you're calling a function with two inputs, but in this case you're not. That's what has MATLAB confused.
(1 + h/(g+1), 1:g)
I think you want this, with one of the parentheses moved from the end of the whole expression to right before 1:g.
(1 + h/(g+1)), 1:g) );
The parentheses that moved ends the body of the anonymous function and the comma separates the two inputs to ARRAYFUN, leaving 1:g as the second input to ARRAYFUN. The parenthesis after 1:g ends the ARRAYFUN call, and the parenthesis at the end of the line (just before the semicolon) ends the SUM call.
Personally in this case I would probably turn that sum-of-arrayfun-of-sum into a simpler double FOR loop to increase readability and clarity. Without some (many) comments you may have trouble remembering what this is doing a week, a month, a year from now.
5 Comments
Walter Roberson
on 3 Dec 2015
X(1:n-h).*e(1:n-h).e(h+1:n).*Xprime(h+1:n) is missing a "*" before the second e()
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!