1. 程式人生 > >Matlab產生二維混合高斯分佈及隨機數

Matlab產生二維混合高斯分佈及隨機數

參考:https://ww2.mathworks.cn/help/stats/gmdistribution.random.html

修改如下:

Create a gmdistribution object and generate random variates.

Define the distribution parameters (means and covariances) of a two-component bivariate Gaussian mixture distribution.

p = [0.4 0.6]; % p is the proportion of two-component Gaussian distribution
mu = [1 2;-3 -5];
sigma = cat(3,[2 .5],[1 1]); % shared diagonal covariance matrix
sigma
sigma(:,:,1) =
    2.0000    0.5000
sigma(:,:,2) =
     1     1

Create a gmdistribution object by using the gmdistribution function. By default, the function creates an equal proportion mixture.

gm = gmdistribution(mu,sigma)
gm = 

Gaussian mixture distribution with 2 components in 2 dimensions
Component 1:
Mixing proportion: 0.400000
Mean:     1     2
Component 2:
Mixing proportion: 0.600000
Mean:    -3    -5

Generate 1000 random variates.

rng('default'); % For reproducibility
[Y,compIdx] = random(gm,1000);

The rng function can be set as a random seed like the rand().

compIdx(i) indicates the mixture component used to generate the ith random variate Y(i,:). Count the number of random variates generated by Component 1.

numIdx1 = sum(compIdx == 1)
numIdx1 = 405

random generates about half of the random variates using Component 1 because gm has equal mixing proportions.

Plot the generated random variates by using scatter.

scatter(Y(:,1),Y(:,2),10,'.') % Scatter plot with points of size 10