Generating two correlated random vectors

孤街醉人 提交于 2019-12-04 15:58:36

As described in this Mathworks article, you can do the following:

  1. Generate two random vectors (i.e a random matrix with two columns). Let's say that you want the distribution of each element in the matrix to be Gaussian with zero mean and unit variance:

    N = 1000;             %// Number of samples in each vector
    M = randn(N, 2);
    

    You can obviously use any distribution to your liking.

  2. Now the trick: multiply the matrix with an upper triangular matrix obtained by the Cholesky decomposition of the desired correlation matrix R:

    R = [1 0.75; 0.75 1]; %// Our correlation matrix, taken from the article
    M = M * chol(R);
    
  3. Extract your random vectors from the modified matrix M:

    x = M(:, 1);
    y = M(:, 2);
    

The cholasky decomposition might fail if there are variable with same correlation. so use SVD. I do it like this. mu is vector having mean of targeted random variables with normal distribution. Sigma is the the required co-variance matrix. n is length of required random variables and d is number of random variables

mu=mu(:)';
[U S V]=svd(Sigma);
S=round(S*1e6)/1e6;
S=sqrt(S);   
s=randn(n, d) * S * U'+mu(ones(n,1),:);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!