简体   繁体   English

用MATLAB创建高斯随机变量

[英]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: Matlab randn从正态分布生成实现,其randn为零,标准差为1.可以通过以下方式简单地生成来自任何其他正态分布的样本:

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 . 请参阅matlab帮助

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. randn(N, 1)创建一个N -by-1向量。

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 . histcx给出的bin的直方图计数 - 你可以使用hist来立即绘制结果,但是在这里我们要将它除以N

pdf contains many useful PDFs, normal is just one example. pdf包含许多有用的PDF,正常只是一个例子。

remember this: X ~ N(mean, variance) 记住这个:X~N(平均值,方差)

randn in matlab produces normal distributed random variables W with zero mean and unit variance. matlab中的randn产生具有零均值和单位方差的正态分布随机变量W. 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. 要将均值和方差更改为随机变量X(使用自定义均值和方差),请遵循以下等式:X = mean + standard_deviation * W请注意,standard_deviation是方差的平方根。

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). 这将生成从N(μ,𝜎)采样的M × N(μ,𝜎)矩阵, = N(2,2)在该特定情况下= N(2,2) )。 For additional information, see normrnd . 有关其他信息,请参阅normrnd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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