Search code examples
matlab

Generate random numbers from empirical cumulative distribution function in MATLAB


I generated an empirical cumulative distribution function in MATLAB via

x = [1, 1.2, ..., 1]
[myECDF, xi] = ecdf(x);

Now I would like to use this ECDF as a basis to draw a set of random numbers from. For example, I would like to do something like this:

y = random(myECDF, 10);  // drawing 10 random numbers from ECDF

Is this possible in MATLAB?


Solution

  • You can use the inverse CDF method. Generate uniformly distributed random variables between 0 and 1 and treat them as CDF outputs. Then use your empirical distribution to find the corresponding values.

    function my_x = my_random(myECDF, xi, N)
        % Generate N uniformly distributed samples between 0 and 1.
        u = rand(N,1);
        % Map these to the points on the empirical CDF.
        my_x = interp1(myECDF, xi, u, 'linear');
    end