簡體   English   中英

如何在直方圖上繪制概率密度函數?

[英]How to plot a probability density function on a histogram?

我的功能名為DicePlot,模擬滾動10個骰子5000次。 在該函數中,它計算每個卷的10個骰子的值的總和,其將是1×5000向量,並且繪制具有邊緣的相對頻率直方圖,以相同的方式選擇,其中直方圖中的每個倉應該表示骰子總和的可能值。

計算1×5000骰子值之和的平均值和標准偏差,並繪制在相對頻率直方圖之上的正態分布的概率密度函數(具有計算的平均值和標准偏差)。

我已經完成了所有工作,但我對如何繪制概率密度函數感到困惑。 任何幫助表示贊賞。 謝謝!

作為參考,該圖應該看起來像! 在此輸入圖像描述

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

我已經從我對前一個問題的回答中添加了代碼,在直方圖的頂部繪制了一個縮放的高斯pdf。 兩個關鍵的增加如下:1)使用hold onhold off以獲得直方圖並繪制在同一圖上。 2)將normpdf的輸出normpdf到適當的大小,使其與直方圖的比例相同。

另外一件事,我不禁注意到你還沒有將我以前的答案中的建議納入你的功能。 有什么特別的原因嗎? 我當然不會為你的問題+1,除非我能看到證據證明你已經將過去的建議納入了你的工作中! 現在你走了,讓我聽起來像我的高中老師! :-)

%#Define the parameters
NumDice = 2;
NumFace = 6;
NumRoll = 500;

%#Generate the rolls and obtain the sum of the rolls
AllRoll = randi(NumFace, NumRoll, NumDice);
SumRoll = sum(AllRoll, 2);

%#Determine the bins for the histogram
Bins = (NumDice:NumFace * NumDice)';

%#Build the histogram
hist(SumRoll, Bins);
title(sprintf('Histogram generated from %d rolls of %d %d-sided dice', NumRoll, NumDice, NumFace));
xlabel(sprintf('Sum of %d dice', NumDice));
ylabel('Count');
hold on

%#Obtain the mean and standard deviation of the data
Mu = mean(SumRoll);
Sigma = sqrt(var(SumRoll));

%#Obtain the Gaussian function using 4 standard deviations on either side of Mu
LB = Mu - 4 * Sigma; UB = Mu + 4 * Sigma;
Partition = (LB:(UB - LB) / 100:UB)';
GaussianData = normpdf(Partition, Mu, Sigma);

%#Scale the Gaussian data so the size matches that of the histogram
GaussianData = NumRoll * GaussianData;

%Plot the Gaussian data
plot(Partition, GaussianData, '-r');
hold off

ps的,如果你不知道先驗的直方圖應該是高斯(因為中心極限定理),那么你可以也使用ksdensity從統計工具箱得到利用核函數的經驗密度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM