# st: Simulation in Stata

 From "Susan Olivia" To statalist@hsphsun2.harvard.edu Subject st: Simulation in Stata Date Wed, 27 May 2009 16:28:44 -0700

Dear Stata list,

I would like to run Monte Carlo simulation using
artificially simulated autocorrelated data. In each
experiment, the only variable that changes is the dependent
variable (Y).

Below is my  programming attempt in creating the Y and am
wondering whether there is more elegant way to implement my
code in Stata. I am a beginner in programming and would
appreciate any programming tips.

Thanks,

Susan

// In this do file, the independent vars and the locations
remain fixed for all iterations, only the dependent variable
changes //

clear

local nrep 250

*qui set obs 100
*gen id_psu = _n

tempvar sdalpha1 sdalpha2
gen `sdalpha1' = uniform()
gen `sdalpha2' = uniform()

* Expand to generate individual observations - here assuming
that each cluster has 10 households *

expand 10
gen no = _n

sort id_psu no
drop no
gen no = _n

gen xcoord = uniform()*100
gen ycoord = uniform()*100
spatwmat, name(W) xcoord(xcoord) ycoord(ycoord) band(0 100)
eigenval(E) standardize

scalar lambda = 0.5
gen constant = 5
mkmat constant

scalar N = _N
matrix Idtot = I(N)

matrix IlambdaW = Idtot-(lambda*W)
matrix invIlambdaW = inv(IlambdaW)

* Generate the predictor & the variable y

gen x = 5 + `sdalpha1'*invnorm(uniform()) + `sdalpha2'
mkmat x

local i = 1

forv i = 1/`nrep'{

gen u`i' = 0.28*invnorm(uniform())
mkmat u`i'

matrix epsilon`i' = invIlambdaW*u`i'

matrix y`i' = constant + x + epsilon`i'
svmat y`i'

local i = `i' + 1

}

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