简体   繁体   中英

Creating Gaussian random variable with MATLAB

通过使用randn函数,我想创建一个高斯随机变量X ,使得X ~ N(2,4)并将该模拟PDF与理论曲线一起绘制。

Matlab randn generates realisations from a normal distribution with zero mean and a standard deviation of 1. Samples from any other normal distribution can simply be generated via:

numSamples = 1000;
mu = 2;
sigma = 4;
samples = mu + sigma.*randn(numSamples, 1);

You can verify this by plotting the histogram:

figure;hist(samples(:));

See the matlab help .

N = 1000;
x = [-20:20];
samples = 2 + 4*randn(N, 1);
ySamples = histc(samples,x) / N;
yTheoretical = pdf('norm', x, 2, 4);
plot(x, yTheoretical, x, ySamples)

randn(N, 1) creates an N -by-1 vector.

histc is histogram count by bins given in x - you can use hist to plot the result immediately, but here we want to divide it by N .

pdf contains many useful PDFs, normal is just one example.

remember this: X ~ N(mean, variance)

randn in matlab produces normal distributed random variables W with zero mean and unit variance. To change the mean and variance to be the random variable X (with custom mean and variance), follow this equation: X = mean + standard_deviation*W Please be aware of that standard_deviation is square root of variance.

N = 1000;
x = [-20:20];
samples = 2 + sqrt(4)*randn(N, 1);
ySamples = histc(samples,x) / N;
yTheoretical = pdf('norm', x, 2, sqrt(4)); %put std_deviation not variance
plot(x, yTheoretical, x, ySamples)

A quick and easy way to achieve this using one line of code is to use :

mu = 2;
sigma = 2;
samples = normrnd(mu,sigma,M,N);

This will generate an MxN matrix, sampled from N(μ,𝜎) , ( = N(2,2) in this particular case). For additional information, see normrnd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM