1. 程式人生 > >相關係數與協方差間的轉換

相關係數與協方差間的轉換

首先,相關係數和協方差間的數學關係為:

其次,上述數學表示式在sas/iml中的演算法表達如下,R為相關係數矩陣,S為對角陣, COV協方差矩陣

其中:

最後,上程式碼:

***** Program 4.10 PROC IML ***********;
***** Converting a correlation matrix to covariance matrix, and vice versa;
***** Example data from Table 4.4 ;
****** Part I: Converting correlation matrix to covariance matrix;
PROC IML;

*** define the correlation matrix;
R={1.00 0.70 0.20,
   0.70 1.00 0.40,
   0.20 0.40 1.00};

*** define the diagonal matrix with standard deviations on the diagonal;
S={15 0 0,
    0 10 0,
    0 0 1};

*** obtain the covariance matrix;	
COV=S*R*S;  

*** print the covariance matrix;
PRINT COV; 
RUN;

***** Part II: Converting covariance matrix to correlation matrix;
PROC IML;

*** define the covariance matrix;
COV={225 105 3,
     105 100 4,
       3   4 1};
	   
*** obtain the matrix with standard deviations on the diagonal;
S=SQRT(DIAG(COV));

*** the inverse of S matrix;
S_INV=INV(S); 

*** obtain correlation matrix;
R=S_INV*COV*S_INV; 

** print out the three matrices;
PRINT COV S R;
RUN;


FROM 《SAS for Monte Carlo Studies》,P96-97