Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: writing mata code more effeciently


From   [email protected] (William Gould, Stata)
To   [email protected]
Subject   Re: st: writing mata code more effeciently
Date   Tue, 21 Feb 2006 08:33:52 -0600

Abdel Rahmen El Lahga <[email protected]> wrote, 

> Is there any solution to rewrite this fragment of my mata code more
> efficiently. My old laptop runs more then 1 hours without finishing the job
> on 50591 obs.

Abdel then included the Mata code.  Abdel has a silly typo in his code and, as
written, his laptop never would have finished.  Abdel typed

                for (i=1; i=nt; i++) {
                        ...
                }

when he meant to type 

                for (i=1; i<=nt; i++) {
                        ...
                }

That is, he typed "i=nt" when he meant "i<=nt".

What the mistaken version did was set i=nt at the start of the loop, increment
i at the bottom of the loop and then, starting the loop again, reset i equal
to nt.  Hence, the endless loop.  I have written a few such loops myself.

Abdel asked for comments, and I have only one suggesion for him:  If he were
to indent his code, and spread it out horizontally, it would be easier to see
what it does, to see how it works, and to spot bugs:

        void fe()
        {
                stata ("drop _all")
                stata ("use c:\data\nicolas\select\sas\testing")
        
                y_init = x_init = s_init = .

                st_view(y_init, .,  "f_week_hours")
                st_view(x_init, ., ("f_lnwage", "m_lnwage", "assetinc"))
                st_view(s_init, ., "s_init")
        
                tmax = 21                // tmax
                n = rows(x_init)/tmax    // nombre d'individus
                nt= rows(x_init)         // nombre total des lignes
                k = cols(x_init)         // nombre de regresseurs
                k
                y = J(nt, 1, 0)
                x = J(nt, k, 0)
                s = s_init
                for (i=1; i<=nt; i++) {
                        if (s[i]=1) {
                                y[i,.] = y_init[i,.]
                                x[i,.] = x_init[i,.]
                        }
                }
        }

Oops, I just spotted another typo.  Abdel typed

                        if (s[i]=1) {

when he meant to type

                        if (s[i]==1) {

A single equal sign means assignment.  == means equality test.

Typos aside, it is well structured and easily understood code.

-- Bill
[email protected]
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index