How to plot a probability density function on a histogram?

21 views (last 30 days)
My function called DicePlot, simulates rolling 10 dice 5000 times. In the function, it calculates the sum of values of the 10 dice of each roll, which will be a 1 × 5000 vector, and plot relative frequency histogram with edges of bins being selected in the same manner where each bin in the histogram should represent a possible value of for the sum of the dice.
The mean and standard deviation are computed of the 1 × 5000 sums of dice values and the probability density function of normal distribution (with the mean and standard deviation that is computed) on top of the relative frequency histogram is plotted.
I have everything done, but i'm confused on how to plot the probability density function. any help is appreciated. thanks!
This is what the graph is supposed to look like
function DicePlot ( throw_num, die_num )
throw_num=5000
die_num= 10
throws = rand ( throw_num, die_num );
throws = ceil ( 6 * throws );
for i = die_num : die_num*6
j = find ( score == i );
y(i-die_num+1) = length ( j ) / throw_num;
end
bar ( x, y )
xlabel ( 'Score' )
ylabel ( 'Estimated Probability' )
score_ave = sum ( score(1:throw_num) ) / throw_num;
score_var = var ( score );
return
end

Accepted Answer

Tom Lane
Tom Lane on 21 Nov 2012
Your code appears to use a variable "score" without defining it.
You can create the histogram by calculating it yourself as you are trying to do, or using the hist function
n = 1000;
x = randn(n,1);
[heights,locations] = hist(x);
But if you want something comparable to a probability density, you need to modify the histogram to have area 1 (or scale up the density instead):
width = locations(2)-locations(1);
heights = heights / (n*width);
bar(locations,heights,'hist')
Now you can superimpose a density such as the standard normal density:
grid = linspace(min(x),max(x));
line(grid,exp(-.5*grid.^2)/sqrt(2*pi),'color','r')
If you have the Statistics Toolbox, you could use normpdf to calculate the density.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!