Given a covarince matrix, generate a Gaussian random variable in Matlab

五迷三道 提交于 2019-12-07 14:35:36

问题


Given a M x M desired covariance, R, and a desired number of sample vectors, N calculate a N x M Gaussian random vector, X in vanilla MATLAB (i.e. can't use r = mvnrnd(MU,SIGMA,cases)).

Not really sure how to tackle this, usually you need a covariance AND mean to generate a Gaussian random variable. I think sqrtm and chol could be useful.


回答1:


If you have access to the MATLAB statistics toolbox you can type edit mvnrnd in MATLAB to see their solution.

[T p] = chol(sigma);
if m1 == c
  mu = mu';
end
mu = mu(ones(cases,1),:);
r = randn(cases,c) * T + mu;

It feels almost like cheating to point this out, but editing MATLAB's source is very useful to understand things in general. You can also search for mvnrnd.m on google if you don't have the toolbox.




回答2:


Example:

% Gaussian mean and covariance
d = 2;             % number of dimensions
mu = rand(1,d);
sigma = rand(d,d); sigma = sigma*sigma';

% generate 100 samples from above distribution
num = 100;
X = mvnrnd(mu, sigma, num);

% plot samples (only for 2D case)
scatter(X(:,1), X(:,2), 'filled'), hold on
ezcontour(@(x,y) mvnpdf([x y], mu, sigma), xlim(), ylim())
title('X~N(\mu,\sigma)')
xlabel('X_1'), ylabel('X_2')

The above code uses functions from the Statistics toolbox (mvnrnd and mvnpdf). If you don't have access to it, consider these replacements (using the same concepts mentioned by others):

mvnrnd = @(mu,S,num) bsxfun(@plus, randn(num,numel(mu))*cholcov(S), mu);

mvnpdf = @(x,mu,S) exp(-0.5*(x-mu)*(S\(x-mu)')) / sqrt((2*pi)^d*det(S));



来源:https://stackoverflow.com/questions/18904308/given-a-covarince-matrix-generate-a-gaussian-random-variable-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!