Obtain a random number from a truncated normal distribution
Show older comments
Hello everyone,
I want to obtain a random number from a truncated normalized distribution. Let's say that we have the following:
magnetization=0.9;
upper_limit=magnetization+magnetization*0.03;
lower_limit=magnetization-magnetization*0.03;
Now, imagine that we want to obtain the aforementioned random number from a truncated normalized distribution such that its mean value will be equal to magnetization, and its standard deviation will be given by, for example, sigma=1. I have seen that I can create my distribution easily from https://es.mathworks.com/help/stats/prob.normaldistribution.truncate.html. But how can I extract from here a random number [magnetization-0.03*magnetization, magnetization+0.03*magnetization] according to this distribution in which not all numbers are equally probable?
I have seen also that there exist this function: https://es.mathworks.com/matlabcentral/fileexchange/53180-truncated-normal-generator, but I am not sure how it works.
Any idea?
Accepted Answer
More Answers (2)
saeid darvishi
on 8 Jan 2021
1 vote
pretruncMean = 0.9;
pretruncSD = 1;
untruncated = makedist('Normal',pretruncMean,pretruncSD);
truncated = truncate(untruncated,pretruncMean-0.03,pretruncMean+0.03);
r = random(truncated,100000,1);
mean(r)
std(r)
histogram(r)
Bruno Luong
on 8 Jan 2021
Edited: Bruno Luong
on 8 Jan 2021
In theory if you range is something +/-0.9*0.03 the maximum possible standard deviation you can reach with a truncated gaussian distribution is
>> 2*0.9*0.03/sqrt(12)
ans =
0.0156
You won't ever able to generate distribution with sigma larger than this limit, such as 1 (or even 0.03).
If you provide more reasonable value, you can use my tool here
desired_std = 0.01 % < 0.0156
r = 0.9+TruncatedGaussian(desired_std,[-1 1]*0.9*0.03,[1 1e6]);
histogram(r)
std(r) % Check
returns as expected
ans =
0.0100

Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!