MATLAB Answers

Maximum likelihood with Heteroskedasticity

2 views (last 30 days)
Anh Tran
Anh Tran on 25 Sep 2020
Commented: Adam Danz on 25 Sep 2020 at 16:38
I am trying to use maximum likelihood estimation for a heteroskedesticity problem. This exact code works for everyone in my class except me (I tried on 3 different computers but with the same license):
%simulate Maximum Likelihood using Monte Carlo simulation
global yhet X2 X3
nobs = 1000; %fix the number of observations
ntrials = 1000; %number of trials
X2 = normrnd(2,0.65,nobs,1);
X3 = normrnd(10,4,nobs,1);
C = ones(nobs,1); %create a constant
X=[C X2 X3];
k=size(X,2); %number of parameters
crit_value=tinv(.975,nobs-k); %t-critical for 95% confidence
%multiplicative: sig_i_sq = exp(alpha1 + alpha2*X_2i)
alphatrue = [.5 .2];
%model: y = beta_1 + beta_2*X_2 + beta_3*X_3 + u
betatrue = [2; 3; 5];
yhet=X*betatrue + u;
%create the function DOESN'T WORK YET
theta_0 = [.5; 1.2; 3.7; .9; -.3]; %some initial values
options=optimset('Display','off','MaxIter',10000,'TolX', 10e-6, 'MaxFunEvals', 10000, 'TolFun',10e-6);
[theta,fval,exitflag,output, grad, hessian] = fminunc(@het_ml,theta_0,options,yhet,X2,X3)
The function file, named "het_ml.m":
function lnl=het_ml(theta,yhet,X2,X3)
global nobs
The error message I get is:
"Error using fminunc (line 383)
Supplied objective function must return a scalar value."
My professor cannot figure out. I don't know who to turn to. Thank you very much for your help!


Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 25 Sep 2020
Edited: Adam Danz on 25 Sep 2020
You are suffering from the side effects of using global variables (incorrectly).
Don't use global variables in Matlab.
Instead, pass the nobs variable in to your objective function as a 5th input variable. Then remove both lines in your code that declare variables as global.
[theta,fval,exitflag,output, grad, hessian] = fminunc(@het_ml,theta_0,options,yhet,X2,X3, nobs)
function lnl=het_ml(theta,yhet,X2,X3,nobs)
Here's why your version was failing.
You were declaring nobs as global in the objective function but not in the script. Even though nobs was defined in the script, it remained empty in the objective function because undefined global variables are empty. Since nobs was empty, the output of the objective function was empty and Matlab threw an error because the objective function must return a scalr value. If nobs was declared as global in the script as well as the objective function, then you would have avoided the error. But you'd still have global variable which frequently cause problems that could have been avoided by never using them.


Anh Tran
Anh Tran on 25 Sep 2020 at 15:10
I followed your instructions and it worked great. Thank you very much for your advice!

Sign in to comment.

More Answers (0)


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!