# How can I generate two correlated random vectors with values drawn from a normal distribution?

361 ビュー (過去 30 日間)
MathWorks Support Team 2011 年 1 月 25 日
コメント済み: Julia Cooper 2019 年 8 月 20 日
I would like to generate two normally distributed random vectors with a specified correlation.

### 採用された回答

MathWorks Support Team 2011 年 1 月 25 日
The idea is to generate a random matrix M with 2 columns (using RANDN) corresponding to the 2 vectors that are to exhibit the desired correlation. That is, the elements of these vectors are drawn from a standard normal distribution. Multiplying M with sigma and adding mu yields a matrix with values drawn from a normal distribution with mean mu and variance sigma^2.
As can be seen from the code below, the trick is to multiply M with the upper triangular matrix L obtained from the Cholesky decomposition of the desired correlation matrix R (which is trivially symmetric and positive definite) in order to set the correlation as needed. In this particular example, the desired correlation is 0.75.
mu = 50
sigma = 5
M = mu + sigma*randn(1000,2);
R = [1 0.75; 0.75 1];
L = chol(R)
M = M*L;
x = M(:,1);
y = M(:,2);
corr(x,y)
The correlation of the resulting vectors can be verified with CORR.

#### 2 件のコメント

Jaskiran Rihal 2019 年 7 月 29 日
Is there any way of doing this so that the correlation is fixed and accurate each time you run a simulation, the Chol method just brings you close to the correlation values set, but it is not exact, and each time you run a simulation the correlation is slightly different between the simulated variables. Is there a way of fixing this?
Julia Cooper 2019 年 8 月 20 日
In order to keep your results fixed each time you run a simulation, try specifying a random seed using the "rng" function:
You may also find the following examples from our documentation helpful, depending on your use case:
Following the methods in these examples may help you achieve more accurate results.
If you have further questions, feel free to contact MathWorks Technical Support at https://www.mathworks.com/support/contact_us.html
who may be able to assist further.

サインインしてコメントする。

### その他の回答 (1 件)

Makarand 2018 年 7 月 18 日
Chol Might fail if covarince matrix is singular or near singular. so use svd I do it as follows where is mu is mean of required random variables.
[U S V]=svd(Sigma);
S=round(S*1e6)/1e6;
S=sqrt(S);
s=randn(n, d) * S * U'+mu(ones(n,1),:);

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!