matlabnormal-distributiontruncated

Drawing pseudorandoms from a truncated normal distribution


Matlab has the function randn to draw from a normal distribution e.g.

x = 0.5 + 0.1*randn() 

draws a pseudorandom number from a normal distribution of mean 0.5 and standard deviation 0.1.

Given this, is the following Matlab code equivalent to sampling from a normal distribution truncated at 0 at 1?

    while x <=0 || x > 1

    x = 0.5 + 0.1*randn();

    end

Solution

  • Using MATLAB's Probability Distribution Objects makes sampling from truncated distributions very easy.

    You can use the makedist() and truncate() functions to define the object and then modify (truncate it) to prepare the object for the random() function which allows generating random variates from it.

    % MATLAB R2017a
    pd = makedist('Normal',0.5,0.1)     % Normal(mu,sigma)
    pdt = truncate(pd,0,1)              % truncated to interval (0,1)
    sample = random(pdt,numRows,numCols)  % Sample from distribution `pdt`
    

    Once the object is created (here it is pdt, the truncated version of pd), you can use it in a variety of function calls.

    To generate samples, random(pdt,m,n) produces a m x n array of samples from pdt.


    Further, if you want to avoid use of toolboxes, this answer from @Luis Mendo is correct (proof below).

    Comparison of @Luis Mendo code results with theoretical results

    figure, hold on
    h = histogram(cr,'Normalization','pdf','DisplayName','@Luis Mendo samples');
    X = 0:.01:1;
    p = plot(X,pdf(pdt,X),'b-','DisplayName','Theoretical (w/ truncation)');