Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • advice on efficiency in doing loop

    hello

    I am trying to do the following loop which would take quite some time. I would be grateful if anyone can comment if there is any part of the code that can be modified to speed up to computation. Thanks!

    Code:
    unab x : x*
    loc xcount = wordcount("`x'")
    forvalues i=1/`xcount' {
    loc xLx="`xLx' x`i' L1_x`i' "
    }
    putmata X=(`xLx') //X store a large number of variables from Stata
    mata xcount=cols(X) 
    mata store=J(xcount*xcount*xcount,7,.) //to store computation results from the mata loop below
    
    mata
        loop=1
        for (a=1; a<=xcount; a++) { 
            for (b=1; b<=xcount ; b++) { 
                for (c=1; c<=xcount ; c++) { 
                    
                    if (a!=b & a!=c & b!=c & a>3 & b>3 & c>3) {
                    
                        x1mean        = mean(select(X[,1], X[,a]:>X[,b] :& X[,a]:<X[,c] :& !(X[,a]:>X[,b] :& X[,a]:<X[,c]) :& X[,1]:<0.4 )) // compute conditional mean on X[,1]
                        
                        x2mean        = mean(select(X[,2], X[,a]:>X[,b] :& X[,a]:<X[,c] :& !(X[,a]:>X[,b] :& X[,a]:<X[,c]) :& X[,1]:<0.4 )) // compute conditional mean on X[,2]
                        
                        x3mean        = mean(select(X[,3], X[,a]:>X[,b] :& X[,a]:<X[,c] :& !(X[,a]:>X[,b] :& X[,a]:<X[,c]) :& X[,1]:<0.4 )) // compute conditional mean on X[,3]
    
                        freq        = colnonmissing(select(X[,1], X[,a]:>X[,b] :& X[,a]:<X[,c] :& !(X[,a]:>X[,b] :& X[,a]:<X[,c]) :& X[,1]:<0.4 )) // compute obs no. on selected X[,1] 
                        
                        store[loop,]=(a,b,c,freq,x1mean,x2mean,x3mean)
                        loop=loop+1
                    }
                    
                    else 1
                }
            }
        }
    
        xa=store[,1]
        xb=store[,2]
        xc=store[,3]
        freq=store[,4]
        x1mean=store[,5]
        x2mean=store[,6]
        x3mean=store[,7]
    
    end
Working...
X