MATLAB: What called this method of generation random sample

acceptance rejectioncumsuminverse cdfrandom number generatorstatistics

Hi all
is the code below represent inverse cdf method?
y is pdf of any distribution
cdf_y = cumsum(y);
sum_y = sum(y);
for j = 1:N
randx = sum_y*rand();
i = 1;
while cdf_y(i) < randx
i = i + 1;
f(j) = x(i); end
please give me explain

Best Answer

  • In the code you show, Mutah, strictly speaking the y vector is not a pdf - a probability distribution function. It is a pmf - a probability mass function. Actually the author of the code has allowed y to be merely proportional to these probabilities, so y is proportional to a pmf. That is because it is dealing with a discrete set of values, not a continuous distribution. For each i, y(i) must be proportional to the probability of a random variable, f, being equal to the corresponding x(i).
    With that understanding, the code is correct and the N-length array, f, will have a statistical distribution in accordance with the y values. The reason the author finds the cumsum(y) and sum(y) is that cumsum(y) is the cumulative sum of the y values and therefore proportional to the cumulative probability that is required of the result, and sum(y) would be the proportionality constant. If on the i-th trip through the for-loop, we have 0 < randx <= cdf_y(1), the while loop will not execute at all and you will get i = 1 which will insert x(1) into f. If cdf_y(1) < randx <= cdf_y(2), the while loop will make just one trip and i will emerge equal to 2, which inserts x(2) into f. This continues to be true all the way to the case cdf_y(end-1) < randx < cdf_y(end) which would then put x(end) into f. Therefore this has the effect of finding the inverse function of cdf_y, that is for each cumulative probability value, randx, it provides the appropriate x(i) value.
    However, it must be said that this code is not very efficient. It does not take advantage of the fact that the cdf_y values are an ascending sequence of values. It should not be necessary to possibly have to run through the entire cdf_y sequence with the while loop seeking the point where each randx fits into the correct interval of cdf_y values. The following code uses the matlab function 'histc' which does take advantage of the ordering in cdf_f and accordingly should be much faster code for large x and y arrays.
    cdf_y = cumsum(y);
    cdf_y = cdf_y/cdf_y(end);
    [~,ix] = histc(rand(N,1),[0;cdf_y]);
    f = x(ix);
    I have assumed here that y and x are column vectors. To understand why this works, you should make a careful study of the 'histc' function at: