连老师您好,下面是我做的一个二重循环,但是我run的结果出来当i =1 和i =2的时候,A11的结果是一样的,也就是说,里面的循环出了问题,导致了A11的前2行的数值一模一样,琢磨了半天,也没弄清楚里面那个循环到底出了什么问题,导致这样的结果,我想可能是跟`i', `j'等标记的顺序有关?非常感谢!
* generating variables
gen g = gdp[_n] - gdp[_n-1]
gen g_percent = [gdp[_n] - gdp[_n-1]]/gdp[_n-1]*100
gen g_year = [(1 + g_percent/100)^4 - 1]*100
gen k = _n
* NOTE: i is the i-th sampling; j is the j time lagging periods; k is the k-th principal components.
*-----------------------------------------*
* k = 1, number of Principal Components is 1.
forvalues j = 1/4{
* Ajk: j denotes the time lagging, k denotes k-th principal components
mat A`j'1 = J(42,1,0)
forvalues i = 1/2{
* selecting our sample
preserve
keep if k < 42 - `j'
* PCA regression
* claiming that this is time series data
encode date, generate(time)
tsset time, quarterly
* gi_year_forwardj: i denotes the i-th sampling; j denotes the j time lagging
gen g`i'_year_forward`j' = F`j'.g_year
keep if g`i'_year_forward`j'!=.
* principal component analysis
display "applying PCA when i = `i', j = `j'"
pca cy*, comp(1)
* Draw the figure
* screeplot
* Prediction
* cyf (ijk)
* i denotes the i-th sampling; j: number of time lagging periods; k: k-th principal components
display "prediction of the scores when i = `i', j = `j'"
predict cyf`i'`j'1, score
* Regression
display "regression of principal components when i = `i', j = `j'"
regress g`i'_year_forward`j' cyf`i'`j'1
* coefijk: i denotes the i-th sampling;
* j deontes number of time lagging periods. k denotes k-th principal components
scalar coef`i'`j'1 = _b[cyf`i'`j'1]
* Bij: i denotes the i-th sampling, j denotes the j time lagging
* k denotes k-th principal components
mat B`i'`j'1 = (coef`i'`j'1)
* obsi: i denotes the i-th sampling
* j denotes the j time lagging; k denotes k-th principal components
scalar obs`i'`j'1 = _N
keep if k == _N
mkmat cyf`i'`j'1, mat(cyf`i'`j'1)
* Gijk: i denotes the i-th sampling, j denotes the j time lagging
* k denotes k-th principal components
display "G is the i-th rows of the matrix Ajk when j = `j', k = `k'"
mat G`i'`j'1 = cyf`i'`j'1*B`i'`j'1 + _b[_cons]
* Ajk: j denotes the time lagging, k denotes k-th principal components
display "A is the matrix when j = `j'"
mat A`j'1[`i',1] = G`i'`j'1
restore
}
}