MATLAB: Obtain a random number from a truncated normal distribution

random numbertruncated normal distribution

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?

Best Answer

You seem to be asking for something like this:
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)
But note that the random numbers are almost uniformly distributed. This is because the untruncated normal is pretty flat in the narrow region where you are truncating. If you reduce the pretruncSD to (say) 0.03, the generated random numbers will look much more like a normal with the tails chopped off.