create a Gaussian distribution with a customize covariance in Matlab

5k Views Asked by At

the Matlab function 'randn' randomize a Gaussian distribution with $\mu= \begin {pmatrix} 0\\0\end{pmatrix}$ and $cov= \begin {pmatrix} 1&0\\0&1\end{pmatrix}$ Ineed to randomize a Gaussian distribution vector with $cov= \begin {pmatrix} 3&1\\1&3\end{pmatrix}$. how can I change the covariance matrix?

1

There are 1 best solutions below

2
On BEST ANSWER

The Statistics Toolbox has a function mvnrnd(see its documentation) to generate jointly Gaussian random variables with specified means and covariance matrix:

N = 10; % desired number of samples of each variable
mu = [10; 10]; % vector of means
cov = [3 1; 1 3]; % covariance matrix
samples = mvnrnd(mu, cov, N);

If you want to do it manually, you can generate independent standard Gaussian RV's (with randn) and apply an affine transformation that will give the desired mean vector and covariance matrix. For that you need to compute the Cholesy decomposition of the latter. See details for example here. Note that the output of Matlab's chol function (see its documentation) needs to be (conjugate-)transposed to conform to the procedure described in the link.

The code would be:

N = 10; % desired number of samples of each variable
mu = [10; 10]; % vector of means
cov = [3 1; 1 3]; % covariance matrix
independent_samples = randn(N, size(cov,1));
A = chol(cov)';
samples = bsxfun(@plus, mu, A*independent_samples.').';

Example realization with your inputs and N=1e5 samples, plotted with

plot(samples(:,1), samples(:,2), '.', 'markersize', .1)
axis square

enter image description here