Matlab: How to generate a 4x1 matrix of random variables, assuming a 4x4 correlation matrix?
I start with 4 time series开发者_高级运维, labelled A, B, C, D.
I generate the following:
- A 4x1 matrix of means.
- A 4x1 matrix of standard deviations.
- A 4x4 correlation matrix, by taking 30 samples from each time series.
What is the Matlab code to generate a 4x1 matrix of random variables, keeping the correlations between the time series intact?
(reason: this is the first stage in a Monte Carlo simulation).
You need just the means vector (call it m
) and the covariance matrix (call it C
). Note that you can get the covariance matrix from the correlation using the equation C = R - m*m'
(or just compute it directly by computing the correlation of the sequences after subtracting their mean).
Then, to get a vector with the covariance C, you generate an IID random vector (say gaussian):
w = randn(4,1)
Then multiply it with the square root of the covariance matrix (call it Q) and add the mean:
v = Q*w + m
You can either use Matlab's sqrt function to compute sqrt(C) or compute it using the SVD or EIG.
[u,d] = eig(C)
Q = u*sqrt(d)*u'
The covariance of v
will be Q*Q'
(=C
) and the mean will be m
See the wikipedia article for the properties of the covariance matrix.
If you have access to the Statistics toolbox, you can use mvnrnd
to generate the numbers.
First calculate the covariance matrix, C
, using cov
or the method described in nimrodm's answer. Then simply call
mvnrnd(m, C)
where m
is your vector of means.
精彩评论