zahra
zahra

Reputation: 175

Generating two correlated random vectors

I want to generate two random vectors with a specified correlation. Each element of the second vector must be correlated with the corresponding element of the first vector and independent of others.

How could I do this in MATLAB?

By the way the elements of the first vector dont have the same distribution, I mean each element of the first vector should have different variances. (the vector is made of 7 variable with different variances.

Upvotes: 2

Views: 6585

Answers (2)

makarand kulkarni
makarand kulkarni

Reputation: 301

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),:);

Upvotes: 0

Eitan T
Eitan T

Reputation: 32930

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);
    

Upvotes: 3

Related Questions