Search code examples
matlabhistogramnormalizationpoisson

Matlab fit poisson function to histogram


I am trying to fit a Poisson function to a histogram in Matlab: the example calls for using hist() (which is deprecated) so I want to use histogram() instead, especially as you cannot seem to normalize a hist(). I then want to apply a poisson function to it using poisspdf() or any other standard function (preferably no toolboxes!). The histogram is probability scaled, which is where the issue with the poisson function comes from AFAIK.

clear
clc

lambda = 5;
range = 1000;
rangeVec = 1:range;

randomData = poissrnd(lambda, 1, range);
histoFigure = histogram(randomData, 'Normalization', 'probability');
hold on

poissonFunction = poisspdf(randomData, lambda);
poissonFunction2 = poisspdf(histoFigure, lambda);

plot(poissonFunction)
plot(poissonFunction2)

I have tried multiple different methods of creating the poisson function + plotting and neither of them seems to work: the values within this function are not consistent with the histogram values as they differ by several decimals.

This is what the image should look like

Example

however currently I can only get the bar graphs to show up correctly.


Solution

  • You're not specifing the x-data of you're curve. Then the sample number is used and since you have 1000 samples, you get the ugly plot. The x-data that you use is randomData. Using

    plot(randomData, poissonFunction)
    

    will lead to lines between different samples, because the samples follow each other randomly. To take each sample only once, you can use unique. It is important that the x and y values stay connected to each other, so it's best to put randomData and poissonFunction in 1 matrix, and then use unique:

    d = [randomData;poissonFunction].';     % make 1000x2 matrix to find unique among rows
    d = unique(d,'rows');
    

    You can use d to plot the data.

    Full code:

    clear
    clc
    
    lambda = 5;
    range = 1000;
    rangeVec = 1:range;
    
    randomData = poissrnd(lambda, 1, range);
    histoFigure = histogram(randomData, 'Normalization', 'probability');
    hold on
    
    poissonFunction = poisspdf(randomData, lambda);
    
    d = [randomData; poissonFunction].';
    d = unique(d, 'rows');
    plot(d(:,1), d(:,2))
    

    With as result:

    enter image description here