Question

I am facing some error to plot the CDF for Triangular distribution; I can plot the histogram using Generating a Triangular distribution in MATLAB, but how do I plot the CDF?

n = 10000; %Random number 
a = 0.26; %Min 
b = 0.46; %Max
c = 0.35; %Mode 
u = rand(n, 1); 
x = zeros(n, 1);
for i = 1:n   
    U = u(i);   
    if U < (c-a)/(b-a);    
        X = a + sqrt(U*(b-a)*(c-a)); 
    else       
        X = b - sqrt((1-U)*(b-a)*(b-c));  
    end    
    x(i) = X; 
end 
hist(x,100)

if a <= x && a <=c
  cdf = (x-a)^2/12
elseif c <= x && x <= b
  cdf = 1-(b-x)^2/4
end

if 0 <= p && p <= 0.75
  INV = a+2*sqrt(3*p);
elseif 0.75 <= p && p <= 1
  INV = b-2*sqrt(1-p)
end
Was it helpful?

Solution

I probably miss something, But why won't the following do? y=hist(x,100); cdf=cumsum(y); plot(cdf)

OTHER TIPS

This is made significantly easier with Probability Distribution Objects in the Statistics toolbox using the makedist(), pdf(), and cdf() functions.

Method 1: Using probability distribution objects (requires Statistics Toolbox)
The probability density function (PDF) is available from pdf(pd,X). The cumulative distribution function (CDF) is obtained with cdf(pd,X).

% MATLAB R2019a
% Setup
a = 0;   % lowerbound
m = 5;   % mode 
b = 12;  % upperbound
pd = makedist('Triangular',a,m,b)     % Create probability distribution object

X = a:0.1:b;                          % domain of X   (useful for plotting)

figure
s(1) = subplot(1,2,1)
    plot(X,pdf(pd,X))
s(2) = subplot(1,2,2)
    plot(X,cdf(pd,X))
sgtitle('X ~ Triangular(a,m,b)')

ylabel(s(1),'PDF')
ylabel(s(2),'CDF')

Triangular distribution PDF and CDF


Method 2: Analytical formulas
You can also use the known analytical formulas (closed form) for the Triangular distribution and directly plot the PDF and CDF that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top