ActiveState Code

Recipe 576512: Generating correlated random numbers


From this great tutorial

For two corelated variables, the formula is much as one would get from intuition about the meaning of correlation with some twist due to normalizing the standard deviation: $X_3 = \alpha X_1 + \sqrt{1-\alpha^2} X_2$ Where $X_1$ and $X_2$ are two independent random variables, and $\alpha$ is the coefficient of correlation between $X_1$ and $X_3$.

In a more general sense:
Let $C$ be the correlation matrix desired. Let $X_1, X_2..., X_N$ be $N$ independent random variables arranged in a row matrix $R = [X_1, X_2,....,X_N]$. Then $Q = RU$ where $U^TU = C$ gives us $N$ random variables $Q = [Y_1, Y_2, ..., Y_N]$ with the required property.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
X = m.matrix(numpy.random.standard_normal((3,1000)))  
C = m.matrix(m.array([[1,.3,.3],[.3,1.,.3],[.3,.3,1.]]))
U = m.cholesky(C)
Y = U*X

#And to test that this works:

m.corrcoef(Y[0,:],Y[1,:])
m.corrcoef(Y[0,:],Y[2,:])
m.corrcoef(Y[1,:],Y[2,:])

Sign in to comment