Search This Blog

Thursday, February 28, 2013

generate random numbers with a given correlation in matlab

Q. How to generate random numbers with a pre specified correlation in Matlab?

Ans. Use mvnrnd() function.This function takes mean (vector of 1xk), covariance (matrix of k x k), number of points (n). The output is an nxk matrix which corresponds to the multivariate normal distribution with the specified mean, covariance.
>> n=1000; mu=[-2,2]; sigma=[1 0.5; 0.5 1]; X = mvnrnd(mu, sigma, n);
>> size(X)
ans =
        1000           2

>> mean(X)
ans =
   -2.0350    2.0157

>> cov(X)
ans =
    0.9950    0.4898
    0.4898    0.9894

>> plot(X(:,1), X(:,2), '.')
>> grid

The problem is underspecified if only the correlation matrix is known. In this case, set the mean to a zero vector, covariance to the given correlation matrix.

Tested in MATLAB (R2012a),  Octave 3.6.2


Anonymous said...

the mean vector is (1xk), not (kx1) as you stated.

Kamaraju Kusumanchi said...

Nice catch. Thanks. I updated the post.