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

# st: loop within Mata to run several optimize() commands

 From Ozgur Ererdem To "statalist@hsphsun2.harvard.edu" Subject st: loop within Mata to run several optimize() commands Date Mon, 26 Dec 2011 07:45:17 -0800

```Dear all,

I am trying to run the optimize() command several times in a row, by using, for each loop, the same optimization program but with different values for the parameters of the functions. Let's say I have  the following:

(a^2)*x + (ln(b))^(0.5)*y - sin(a) + beta[1] = 0
(b^3)*y - tan(a^2)*x - beta[2] = 0

for each loop, I have different values for (a, b, beta[1], beta[2]), and each loop calculates (x, y) that maximize this non-linear system. The values for a, b and betas are kept in a matrix, and there is an ID for each set of (a, b, beta[1], beta[2]). In other terms, for each ID I have, say:

ID            a              b             beta
1              2              0.5          0.9
1              2              0.5          2
2              1.3          1.1          0.5
2              1.3          1.1          0.7

So basically, what I have to do, for each loop, is to keep only the (a, b, betas) set I need with "keep if ID==something" and then run the optimization.

However I tried several ways to run this loop, and none of them worked so far:
- Tried to run a foreach loop from Stata, with a mata section in the middle. But realized that this was impossible, because the "end" command you have to put at the end of your Mata entries simply stops the Stata loop itself.
- Tried to trick Mata by using the old-style "goto" command, but I am getting an error message (system error UPDaddr)
- The Mata loop (for (i=.; i<=.; i++)) does not allow for the command "Mata Stata use "..dta"", which I need to call the (a,b, beta) matrix at each loop.

I would appreciate any help you can give me.

Thank you in advance

Ozgur Kaan Ererdem
Economist
ECOPA
www.ecopa.com

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