相对频率直方图和概率密度函数

时间:2012-11-21 18:04:02

标签: matlab histogram probability dice

名为DicePlot的函数模拟滚动10个骰子5000次。

该函数计算每个卷的10个骰子的值的总和,其将是1⇥5000向量,并且绘制相对频率直方图,其中选择二进制位的边缘,其中直方图中的每个二进制位表示可能的值。为骰子的总和。

将计算1×5000个骰子值之和的平均值和标准差,并绘制在相对频率直方图之上的正态分布的概率密度函数(计算平均值和标准差)。

以下是我的代码到目前为止 - 我做错了什么?图表显示但顶部没有额外的红线?我看了这样的答案,我认为我不会像高斯函数那样绘制任何东西。

% function[]= DicePlot()
for roll=1:5000
    diceValues = randi(6,[1, 10]);
    SumDice(roll) = sum(diceValues);
end
distr=zeros(1,6*10);
for i = 10:60
    distr(i)=histc(SumDice,i);
end
bar(distr,1)
Y = normpdf(X)
xlabel('sum of dice values')
ylabel('relative frequency')
title(['NumDice = ',num2str(NumDice),' , NumRolls = ',num2str(NumRolls)]); 
  end

应该看起来像 enter image description here

但看起来像是

enter image description here

2 个答案:

答案 0 :(得分:2)

红线不在那里,因为你没有密谋。查看normpdf的文档。它计算pdf,它没有绘制它。所以问题是如何将这一行添加到图中。这个问题的答案是google“matlab hold on”。

答案 1 :(得分:2)

这里有一些代码可以让你朝着正确的方向前进:

% Normalize your distribution 
normalizedDist = distr/sum(distr);
bar(normalizedDist ,1); 
hold on

% Setup your density function using the mean and std of your sample data
mu   = mean(SumDice);
stdv = std(SumDice);
yy   = normpdf(xx,mu,stdv);
xx   = linspace(0,60);

% Plot pdf
h = plot(xx,yy,'r'); set(h,'linewidth',1.5);
相关问题