4

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)
horchler
  • 18,384
  • 4
  • 37
  • 73
Sari
  • 101
  • 1
  • 2
  • 5

2 Answers2

3

The most straightforward way to create a cumulative distribution from data is to generate an empirical CDF. The ecdf can do this directly. By default, this doesn't require one to produce a histogram for a dataset:

x = randn(1000,1);
ecdf(x);

Empirical CDF

However, if you want a lower resolution CDF, you can use histogram directly with the 'cdf' normalization option:

x = randn(1000,1);
nbins = 25;
histogram(x,nbins,'Normalization','cdf');

CDF histogram option

You might find the 'cumcount' option useful too. See the documentation for ecdf and histogram for details on how to extract and use the output from these functions.

horchler
  • 18,384
  • 4
  • 37
  • 73
2

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
ibezito
  • 5,782
  • 2
  • 22
  • 46
  • i keep getting this error "CUMSUM supports only numerical or logical inputs. " – Sari Apr 03 '16 at 11:59
  • The reason: the name of the MATLAB's function which calculates histogram is called "hist" and not "historgam". I will supply the full code. – ibezito Apr 03 '16 at 12:00
  • Also, don't forget to normalize your histogram. – ibezito Apr 03 '16 at 12:04
  • 1
    No, [`histogram`](http://www.mathworks.com/help/matlab/ref/histogram.html) is the name of the function. [`hist`](http://www.mathworks.com/help/matlab/ref/hist.html?refresh=true) has been deprecated for a few years now (with a fairly strong suggestion to no longer use it). `histogram` returns a struct where `h.Values` is equivalent to what `hist` returns. – horchler Apr 03 '16 at 16:24
  • @horchler I didn't know that. Thank you for your comment, I updated my answer accordingly. – ibezito Apr 04 '16 at 08:03