Search code examples
matlabprobability-densitycdfecdf

How to compute CDF from a given PMF in Matlab


For a given PMF p=f(\theta) for \theta between 0 and 2\pi, i computed the CDF in Matlab as

theta=0:2*pi/n:2*pi
for i=1:n
cdf(i)=trapz(theta(1:i),p(1:i));
end

and the result is verified.

  1. I tried to do the same with cumsum as cdf=cumsum(p)*(2*pi)/n but the result is wrong. why?

  2. How can i compute the CDF if the given PMF is in 2D asp=f(\theta,\phi) ? Can i do it without going into detail as explained here ?


Solution

  • In 1D case you can use cumsum to get the vectorized version of loop (assuming that both theta and p are column vectors):

    n = 10;
    theta = linspace(0, 2*pi, n).';
    p = rand(n,1);
    cdf = [0; 0.5 * cumsum((p(1:n-1) + p(2:n)) .* diff(theta(1:n)))];
    

    In 2D case the function cumsum will be applied two times, in vertical and horizontal directions:

    nthet = 10;
    nphi = 10;
    theta = linspace(0, 2*pi, nthet).';     % as column vector
    phi = linspace(0, pi, nphi);            % as row vector
    p = rand(nthet, nphi);
    cdf1 =  0.5 * cumsum((p(1:end-1, :) + p(2:end, :)) .* diff(theta), 1);
    cdf2 =  0.5 * cumsum((cdf1(:, 1:end-1) + cdf1(:, 2:end)) .* diff(phi), 2);
    cdf = zeros(nthet, nphi);
    cdf(2:end, 2:end) = cdf2;