Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# st: Re: Mata maximum likelihood error on trivial regression

 From David Chan <[email protected]> To [email protected] Subject st: Re: Mata maximum likelihood error on trivial regression Date Mon, 22 Aug 2011 14:58:17 -0400

```Hi all,

I have discovered the solution, thanks to Jeffrey Pitblado:

The line

sd=exp(b[|j|])

should be

sd = exp(moptimize_util_xb(ML,b,2))

The function -moptimize_util_xb()- does some extra calculation that allows
-ml- (really it's -moptimize()-) to properly take numerical derivatives.
By explicitly pulling the value of 'b[|j|]', you are not getting that extra
calculation into you 'sd' variable.

Thanks,
Dave

On Fri, Aug 19, 2011 at 12:23 PM, David Chan <[email protected]> wrote:
>
> Hi all,
>
> I'm having problems with doing maximum likelihood in Mata. Even in the most basic setup, I'm getting the error,
>
> "could not calculate numerical derivatives -- flat or discontinuous region encountered
> r(430)."
>
> I'm almost certain that this is not because of problems with the data or model, but it probably has something to do with a naive programming error. I'm simulating my own data, and I'm testing out the program on a very simple linear regression model,
>
> y=Ey+zeta_k+epsilon,
>
> where epsilon is a random, normally distributed term, and Ey and zeta_k are both observed regressors (both with coefficient 1).
>
> After simulating data according to this model, simple regression,
>
> > reg y Ey zeta_k"
>
> works fine. Also when I code up the trivial MLE in Stata as an ado program, I have no problems:
>
> > program mynormal_lf
> >     args lnfj mu sigma
> >    qui replace `lnfj'=ln(normalden(\$ML_y1,`mu',`sigma'))
> > end
> > ml model lf mynormal_lf (mu: lnlos = Ey zeta_k) /sigma
> > ml maximize
>
> However, when I code it up in Mata, using the code below, I always get the error message, even when I set the initial values at the true parameters:
>
> > mata:
> > void mydynamic_lf(transmorphic scalar ML, real rowvector b, ///
> >                  real colvector lnfj)
> > {
> >     real colvector y, xb
> >     real colvector sd
> >     y=moptimize_util_depvar(ML,1)
> >     xb=moptimize_util_xb(ML,b,1)
> >     j=moptimize_util_eq_indices(ML,2)
> >     sd=exp(b[|j|])
> >     lnfj=ln(normalden(y,xb,sd))
> > }
> > end
> > ml model lf mydynamic_lf() (mu: lnlos = Ey zeta_k) /sigma
> > ml maximize
>
> I've tried renaming the variables within Mata, as well as changing the variable declaration (e.g., calling "sd" a scalar rather than a colvector), but nothing seems to work.
>
> Does anyone know what I'm doing wrong?
>
> Dave
>

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```