By using randn
function I want to create a Gaussian random variable X
such that X ~ N(2,4)
and plot this simulated PDF together with theoretic curve.

- 2,856
- 7
- 21
- 41

- 19
- 1
- 1
- 4
-
Possible duplicate of [Draw Normal Distribution Graph of a Sample in Matlab](https://stackoverflow.com/questions/11831690/draw-normal-distribution-graph-of-a-sample-in-matlab) – SecretAgentMan Jul 08 '19 at 14:49
-
Also see [this answer's code](https://stackoverflow.com/a/52902148/8239061) which has an example to both generate samples to estimate the PDF and compare with the theoretical PDF. You can also repeat [this example](https://stackoverflow.com/a/53876868/8239061) but leave off the *truncation*. – SecretAgentMan Jul 08 '19 at 14:56
-
Possible duplicate of [Random Numbers with Gaussian and Uniform Distributions in matlab](https://stackoverflow.com/q/13844944/8239061) – SecretAgentMan Jul 08 '19 at 14:57
4 Answers
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.

- 2,082
- 3
- 28
- 32
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.

- 241
- 1
- 3
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)

- 1
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
.

- 2,856
- 7
- 21
- 41

- 21
- 6
-
How is this different from [this answer](https://stackoverflow.com/a/13101180/8239061) or [this one](https://stackoverflow.com/a/20570900/8239061)? Plus OP wanted N(2,4), not N(2,2). Also, question explicitly wants to look at the empirical [PDF](https://en.wikipedia.org/wiki/Probability_density_function) and compare to theoretical one. – SecretAgentMan Jul 08 '19 at 14:59