1

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.

user191919
  • 724
  • 1
  • 9
  • 27
  • possible duplicate of [Generate random number with given probability matlab](http://stackoverflow.com/questions/13914066/generate-random-number-with-given-probability-matlab) – Daniel Feb 28 '15 at 15:19
  • What do you mean by "evaluate density"? `hist`? `histc`? `ksdensity`? – A. Donda Feb 28 '15 at 16:25
  • Say that my histogram is a discretized version of a continuous density. How can I evaluate f(x) from the histogram? – user191919 Feb 28 '15 at 16:49
  • The histogram _is_ an estimation of the probability density. You only need to normalize, dividing by {sample size times bin width}, so that the area is 1. Then, if you need to evaluate the probability density at intermediate values, use interpolation – Luis Mendo Feb 28 '15 at 18:22
  • Yes, any quick way to this interpolation? – user191919 Feb 28 '15 at 19:32

2 Answers2

1

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

Harijoe
  • 1,771
  • 1
  • 16
  • 27
0

A popular way is to use kernel density estimation. The simplest way to do this in Matlab is using ksdensity.

3lectrologos
  • 9,469
  • 4
  • 39
  • 46