How to make a CDF from a histogram in MATLAB

Sari picture Sari · Apr 3, 2016 · Viewed 9k times · Source

I am trying to create function that takes a histogram and makes a CDF from it. However I cannot use the cdfplot function in Matlab.

How would I go about doing this?

This produces the input histogram:

x = randn(1000,1);
nbins = 25;
h = histogram(x,nbins)

Answer

ibezito picture ibezito · Apr 3, 2016

Use MATLAB's cumsum function, after normalizing the histogram.

hNormalized = h.Values / sum(h.Values);
cdf = cumsum(hNormalized)

The full code:

x = randn(1000,1);
nbins = 25;
h = histogram(x,nbins);
hNormalized = h.Values / sum(h.Values);
cdf = cumsum(hNormalized);

Results with smaller nBins (nBins = 8):

hNormalized =

0.0210    0.0770    0.1930    0.2830    0.2580    0.1250    0.0370    0.0060

cdf =

0.0210    0.0980    0.2910    0.5740    0.8320    0.9570    0.9940    1.0000