How to plot PDF and CDF for a normal distribution in matlab

25.5k views Asked by At

I couldn't find a function in matlab that implement gets mean and standard deviation of normal distribution and plot its PDF and CDF.

I am afraid the two functions I have implemented bellow are missing something, since I get maximal value for pdfNormal which is greater than 1.

function plotNormPDF(u,s,color)
    mu = u; 
    sigma = s; 
    x = (mu - 5 * sigma) : (sigma / 100) : (mu + 5 * sigma); 
    pdfNormal = normpdf(x, mu, sigma);
    string = 'the maximal pdfNormal is';
    string = sprintf('%s :%d', string,max(pdfNormal));
    disp(string)
    plot(x, pdfNormal/max(pdfNormal),color); 
end

And for the CDF norm

function plotNormCDF(u,s,color)
    mu = u; 
    sigma = s; 
    x = (mu -  5*sigma) : (sigma / 100) : (mu + 5*sigma); 
    pdfNormal = normpdf(x, mu, sigma);
    plot(x,cumsum(pdfNormal)./max(cumsum(pdfNormal)),color)
end

Here is an example for using both:

plotNormCDF(0.2, 0.1,'r')
plotNormPDF(0.2, 0.1,'r')

enter image description here

enter image description here

2

There are 2 answers

0
A. Donda On BEST ANSWER

Your function plotNormPDF is correct except that you should not divide by the maximum. As David Marx wrote, there is no upper constraint on the values that a probability density function can attain, only a constraint regarding its integral over the range of possible values.

function plotNormPDF(u,s,color)
mu = u;
sigma = s;
x = (mu - 5 * sigma) : (sigma / 100) : (mu + 5 * sigma);
pdfNormal = normpdf(x, mu, sigma);
string = 'the maximal pdfNormal is';
string = sprintf('%s :%d', string,max(pdfNormal));
disp(string)
plot(x, pdfNormal,color);
end

Your function plotNormCDF is correct in principle, but probably not very precise because it approximates an integral by a cumulative sum. Better to use the function normcdf. Normalization of the maximum to 1 here is neither necessary nor does it have an effect.

function plotNormCDF(u,s,color)
mu = u;
sigma = s;
x = (mu -  5*sigma) : (sigma / 100) : (mu + 5*sigma);
cdfNormal = normcdf(x, mu, sigma);
plot(x,cdfNormal,color)
end
2
juliohm On

You don't need all that code, look how simpler it is:

mu = 0.2; sigma = 0.1;
x = linspace (mu-4*sigma, mu+4*sigma);
plot(x, normpdf (x,mu,sigma))
plot(x, normcdf (x,mu,sigma))