[Matlab] Generating random numbers with given covariance matrix
We are given a covariance matrix, and we’d like to generate n vectors, whose coordinates’ covariance matrix is equal to given. We also like each coordinate to have given mean.
Here is a code:
function numbers = randomcov(n, covMatrix, offset) x=randn(n,length(covMatrix(1,:))); numbers = x*inv(chol(cov(x)))*chol(covMatrix); for i=1:length(offset) numbers(:,i) = offset(i)+numbers(:,i)-mean(numbers(:,i)); end end |
Usage:
n – number of vectors to generate
covMatrix – given covariance matrix
offset – vector of means of each coordinate
Example:
>> n = 1000 n = 1000 >> covMatrix = [1 0.6 0.3; 0.6 4 0.5; 0.3 0.5 9] covMatrix = 1.0000 0.6000 0.3000 0.6000 4.0000 0.5000 0.3000 0.5000 9.0000 >> offset= [4, 7, 5] offset = 4 7 5 >> res = randomcov(1000, [1 0.6 0.3; 0.6 1 0.5; 0.3 0.5 9], [4, 7, 5]); >> length(res) ans = 1000 >> res(1:10,:) ans = 5.4045 6.7922 13.7702 3.2959 7.8065 4.1698 4.4234 7.5814 8.2764 5.1770 9.1141 7.6232 3.0880 5.7971 6.7749 2.8736 6.6350 7.4795 4.1235 7.1429 4.4354 4.2488 7.5810 2.4269 2.7958 7.3045 8.3019 3.7704 6.5484 7.3827 >> cov(res) ans = 1.0000 0.6000 0.3000 0.6000 1.0000 0.5000 0.3000 0.5000 9.0000 >> mean(res) ans = 4.0000 7.0000 5.0000 |