# Generating a Gaussian dataset in MATLAB

I want to generate a bivariate Gaussian dataset. The dataset includes a total of 800 results drawn randomly from four two-dimensional Gaussian classes with means $(-3,0)'$, $(0,0)'$, $(3,0)'$, and $(6,0)'$, all with the same variance-covariance matrix

$$\Sigma = \pmatrix{0.5 & 0.05 \\ 0.05 &0.5}.$$

How can I do that in MATLAB? I'm not expert in MATLAB.

Statistics Toolbox offers a function to sample from a bivariate Gaussian

% Specific a covariance matrix
SIGMA = [.5 .05; .05 .5 ];

% Generate four bivariate normal distributions with specified means
temp = mvnrnd([-3 0], SIGMA,800);
temp(:,3:4) = mvnrnd([-3 0],SIGMA,800);
temp(:,5:6) = mvnrnd([3 0], SIGMA, 800);
temp(:,7:8) = mvnrnd([6 0], SIGMA, 800);


First, the means.

mu = 3*floor(rand(1,800)*4) - 3; % first dimension means
mu = [mu; zeros(1,800)]; % add second dimension


Given info on multivariate normal random deviate generation, Cholesky factorization, and MATLAB's builtin normal random number generator, you'll be able to understand the code below. It generates a 2-by-800 matrix, each column of which is sampled from the mixture distribution you specified in the question.

SIGMA = [.5 .05; .05 .5];
A = chol(SIGMA);
randvec = mu + A'*randn(2,800);


I have not tested this code properly -- I don't have a local copy of MATLAB. I tried it in an Octave web interface and it seemed to work.

I found answer as follow: (Thanks all)

Sigma=[0.5 0.05; 0.05 0.5];
z=mvnrnd([-3 0],Sigma,200);
x=mvnrnd([0 0],Sigma,200);
c=mvnrnd([3 0 ],Sigma,200);
v=mvnrnd([6 0 ],Sigma,200);
samples=[z; x; c; v];
plot(samples(:,1),samples(:,2),'*');

• Thank you for sharing your solution, Reza. Because it is essentially identical to the one offered earlier by @Richard Willey, why don't you mark his reply as accepted? (Upvotes and acceptance are tangible ways in which thanks can be offered on this site.) – whuber Apr 12 '12 at 14:09
• @whuber Thanks for your idea. My reputation is not enough for up voting yet. But OK, you are right about answers, essentially these three answers have identical results. – PHPst Apr 12 '12 at 15:43
• (+1) Your reputation is now high enough to vote replies and questions up :-). – whuber Apr 12 '12 at 16:20
% Specific a covariance matrix
SIGMA = [.5 .05; .05 .5 ];

% Generate four bivariate normal distributions with specified means
temp = mvnrnd([-3 0], SIGMA,800);
temp(:,3:4) = mvnrnd([-3 0],SIGMA,800);
temp(:,5:6) = mvnrnd([3 0], SIGMA, 800);
temp(:,7:8) = mvnrnd([6 0], SIGMA, 800);