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

# Re: st: programming in stata - problems with optimize

 From Matthew Baker To statalist@hsphsun2.harvard.edu Subject Re: st: programming in stata - problems with optimize Date Sat, 23 Jul 2011 10:49:38 -0400

```While it is hard to say what exactly is wrong without a snapshot of
the data, I think the biggest potential problem is that it looks like
you are trying to find the extremum of an ill-defined function. That
is, if one wants to use an optimizer to find the solution to something
like f(x)=a, one cannot use f(x)-a as the objective function in an
optimizer; one must use (f(x)-a)^2 and find the minimum, say.

A toy example roughly along the lines of the problem is as follows,
where I have modified the objective to be
f = ((Nx' * normal(hlp)) - Sk1)^2
and (just to be safe) explicitly coded that the optimizer is to find a
minimum of f using
optimize_init(which(S,"min")

/* begin example */
clear all
set obs 100
gen Xbeta=.5+invnormal(runiform())
gen N=1/100
mata
X=st_data(.,"Xbeta")
Nx=st_data(.,"N")
void mymodelb(todo,mu2,f,g,H)
{
external Nx,X
hlp=(mu2:-X)
f=(Nx'*normal(hlp)-.501)^2
}
S=optimize_init()
optimize_init_evaluator(S,&mymodelb())
optimize_init_params(S,0)
optimize_init_which(S,"min")
mu2=optimize(S)
mu2
end
/* end example */

Hope that helps!

Matt Baker

On Fri, Jul 22, 2011 at 4:19 PM, A.J van der Vlist <vlist001@hotmail.com> wrote:
>
> Dear Statalisters,
>
> I encouter problems in optimizing function f:
>
> I would like to solve for mu:
>
>  sum over i {  Nx_i' * (mu - Xbeta_i) } = Sk
>
> Nx = [n x 1] , vector of {1/n}'s  in order to sum over i
> mu = parameter
> Xbeta = [n x 1] vector of fitted values
> Sk = scalar
>
> This is what I tried:
>
> scalar Sk1=Sm1_SRA
> mata:
> X=st_data(.,"Xbeta")
> Nx=st_data(.,"Nxi")
> void mymodelb(todo, mu2, f, g, H)
> {
> external Nx, X
> hlp=(mu2 :- X)
> f = (Nx' * normal(hlp)) - Sk1
> }
> S = optimize_init()
> optimize_init_evaluator(S, &mymodelb())
> optimize_init_params(S, 0)
> mu2 = optimize(S)
> problem:
>
> 1) I get problems when running with Sk1 in f
> 2) when I substitute for Sk1 =0.501 in f the code will give a result - yet unreasonable high +e11
>
> Suggestions are very welcome.
>
> Arno
> *
> *   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/

--
Dr. Matthew J. Baker
Department of Economics
Hunter College and the Graduate Center, CUNY

*
*   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/
```