Search code examples
matlabhistogramkernel-density

Custom histogram density evaluation in MatLab


Does MatLab have any built in function to evaluate the density of a random variable from a custom histogram? (I suspect there are probably lots of ways to do this, I am just looking to see if there is already any builtin MatLab functionality). Thanks.


Solution

  • The function hist gives you an approximation of the probability density you are evaluating.

    If you want a continuous representation of it, this article from the Matlab documentation explains how to get one using the spline command from the Curve Fitting Toolbox. Basically the article explains how to make a cubic interpolation of your histogram.

    The resulting code is :

    y = randn(1,5001); % Replace y by your own dataset
    
    [heights,centers] = hist(y);
    hold on
    n = length(centers);
    w = centers(2)-centers(1);
    t = linspace(centers(1)-w/2,centers(end)+w/2,n+1);
    dt = diff(t);
    Fvals = cumsum([0,heights.*dt]);
    F = spline(t, [0, Fvals, 0]);
    DF = fnder(F);
    hold on
    fnplt(DF, 'r', 2)
    hold off
    ylims = ylim;
    ylim([0,ylims(2)]);
    

    Continuous representation of Gaussian density