MATLAB: How to generate random numbers in mixture normal distribution (considering weight)

distributionimage processingmatrixmeanrandomstandard deviationweight

For a mixture normal distribution the code below is used (for 1000 sample):
x1= mu(1) + std(1)*randn(1000,1)
x2= mu(2) + std(2)*randn(1000,1)
But, I wan to take the respected weight into account, Wi=[0.8 0.2], for instance.
I tried this code, but when I plot the PDFs of them, it gives me wrong curves.
x1= Wi(1)*(mu(1) + std(1)*randn(1000,1));
x2= Wi(2)*(mu(2) + std(2)*randn(1000,1));
I was wondering how I can solve this problem?

Best Answer

Does this do what you intend?
mu = [0 5];
std = [1 1];
N = 1000;
r = rand(N,1);
x1= (r >0.8).*(mu(1) + std(1)*randn(N,1));
x2= (r<=0.8).*(mu(2) + std(2)*randn(N,1));
x = x1+x2;
figure
histogram(x,99)