# st: Using for within Mata optimize to loop over observations

 From Bob Hammond To statalist@hsphsun2.harvard.edu Subject st: Using for within Mata optimize to loop over observations Date Mon, 16 Feb 2009 15:17:57 -0500

```All,

```
Using Mata's optimize(), I want to find the x that maximizes f(x,z) with respect to x, where z is a variable in my existing data set. My thought is to loop over observations, feeding in the z of the current observation and storing the optimum in the current observation's x. My problem is that I cannot get a for loop to work within the optimize code. Another solution is to differentiate f(x,z) with respect to x and find the x that makes the derivative equal to zero for each z in the data set. This works perfectly for several versions of f(x,z) but I am now working with an f(x,z) that is much more easily expressed without having to differentiate. Also, since I am currently trying to learn Mata, I would like to know how to use loops within the optimize code since it seems like a reasonable thing to do.
```
```
The most closely related solution I found in a search of the archives is http://www.stata.com/statalist/archive/2007-12/msg00551.html but I haven't been able to translate this solution to my problem of loop over observations.
```
```
The following code uses a trivial f(x,z) and shows how to do it with mm_root() (which works) and one way that seems like it might work with optimize() (which does not). I've tried several versions of the optimize() approach (basically moving around the "for(...)") but it always either gives an error, uses only the first observation, or uses only the last observation.
```
```
Ben Jann's moremata package is required to use mm_root() (-findit moremata-).
```
Thanks in advance for any thoughts,

Bob

>>>>>>>>>>>
clear
clear mata
set obs 10
gen double z  = runiform()
gen double x  = .
gen double x2 = .
mata:
function myfunc(x,z) return(-2*(x-z))
for(i=1;i<=st_nobs();i++) {
z = st_data(i,"z")
rc = mm_root(x = ., &myfunc(), 0, 1, 0, 1000, z)
st_store(i,"x",x)
}
void eval0(todo, x, v, g, H)
```
{ z = st_data(i,"z")
```       v = -(x-z)^2
}
for(i=1;i<=st_nobs();i++) {
S = optimize_init()
optimize_init_evaluator(S, &eval0())
optimize_init_params(S, 0)
x = optimize(S)
st_store(i,"x2",x)
}
end
list

--
------------------------------------------------------------------------
Bob Hammond
Department of Economics
North Carolina State University
Office: (919) 513-2871
Fax: (919) 515-7873
http://www4.ncsu.edu/~rghammon/

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