Bookmark and Share

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


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Using loop in Mata?


From   Phil Schumm <[email protected]>
To   <[email protected]>
Subject   Re: st: Using loop in Mata?
Date   Tue, 9 Jul 2013 06:09:09 -0500

On Jul 9, 2013, at 3:11 AM, Henk-Wim de Boer <[email protected]> wrote:
> I am using Mata and I want to put the following code into a loop:
> 
> U_1 = colshape(U_1,6)
> U_2 = colshape(U_2,6)
> U_3 = colshape(U_3,6)
> U_4 = colshape(U_4,6)
> U_5 = colshape(U_5,6)
> U_6 = colshape(U_6,6)
> U_7 = colshape(U_7,6)
> U_8 = colshape(U_8,6)
> U_9 = colshape(U_9,6)
> U_10 = colshape(U_10,6)
> 
> In STATA, I would use a local variable:
> 
> forvalues r=1(1)10 {
> gen U_`r' = ....
> }
> 
> Obviously, this does not work in MATA. Does anyone know how to code this in a proper way in MATA?


It's difficult to give an answer here without seeing more of the context, but if you've got variables U_1, U_2, ..., U_10, then that's a pretty good indication that you should rethink how you are structuring the data in your program.  Nick suggested pointers, and indeed an array of pointers, each pointing to one of the matrices U_1, U_2, etc. might likely be your best choice.  This then gives a basis for looping over the matrices, by looping over the items in the array.  Alternatively, you could consider using an associative array, but with keys 1, 2, 3, etc. there's really no value in doing that.  If, however, your 1, 2, 3 simply stand for something else, then this might make sense.


-- Phil


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


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index