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: Loops in Mata


From   [email protected] (William Gould, StataCorp LP)
To   [email protected]
Subject   Re: st: Loops in Mata
Date   Wed, 26 Jan 2011 09:03:11 -0600

"gsborker" <[email protected]> writes, 

> I am trying to do the following in mata
> 
> mata
> 
>       for (i=1; i<=379; i++) {
>               
>               xi = st_data(.,"Pi") ;
>               yi = (xi)' ;
>               polyroots(yi) ;
>               
>               }
> end

The problem is with the statement 

        xi = st_data(., "Pi")

As others have written, gsborker is probably assuming that Pi is somehow 
interpreted as P`i' when it is not.  changing the line to be 

        xi = st_data(., "P`i'")           <---- will not work

will not work because P`i' is Statapeak.  Mata does not understand macros 
in the same way as Stata does.  The correct solution is 

       name_to_use = sprintf("P%g", i)
       xi = st_data(., name_to_use)

Another way to code would be 

       name_to_use = "P" + strofreal(i)
       xi = st_data(., name_to_use)

It does not matter which is used.  Either way, the idea is to construct 
the desired variable name in Mata string variable name_to_use.

This can be combined into a single line, 

       xi = st_data(., sprintf("P%g", i))

or 
 
       xi = st_data(., "P" + strtoreal(i))
       

That is just a matter of style.

Indeed, the entire code fragment could be combined, 

        for (i=1; i<=379, i++) {
             polyroots(st_data(., sprintf("P%g", i))')
        }

or 

        for (i=1; i<=379, i++) {
             polyroots(st_data(., "P" + strtoreal(i))')
        }

As I said, this is just a matter of style.  The advantage of gsborker's 
multiline style is that it may be easer to understand.

-- Bill
[email protected]
*
*   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/


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