如何将矩阵中数字的频率显示为直方图?

问题描述 投票:0回答:1

我正在编写一个模拟来显示负二项式分布。 我有一个代码,本质上是抛硬币并计算次数,直到得到 4 个硬币。然后将该计数放入矩阵中,整个过程可以根据需要重复多次。 所以矩阵最终应该看起来像 [ 5 9 7 11 6 6 7 8 ...] 我想在直方图上显示某个数字出现的次数。因此,如果需要 5 次尝试才能翻转,而我的 3 个实验都需要 5 次尝试,那么我想要一个在 5 处高度为 3 的直方图。

我使用 hist() 函数取得了一定的成功,但无论出于何种原因,垃圾箱与数字不一致。这样,历史记录从 4 开始,然后下一个从 4.8 开始,下一个从 5.6 开始,这对我的数据没有意义,因为只有整数。

这是我的代码。我知道我可以在 hist 中拥有更多参数,并且可以标准化分布,但我现在并不担心这一点。我只想知道如何制作 binwidth 间隔为 1 而不是 0.8 或其他任何值的直方图。直方图尝试的图片:) 感谢您的帮助。 我知道Matlab有直方图函数,但我在Octave中编码,因为我是一个破产的大学生。enter image description here

我查遍了互联网,没有任何帮助。

A = zeros(1,100) 
headsCounter = 0
success = 4
tries = 0
ii = 2
largestTries = 0
while(ii<=length(A)) %for whatever reason, it would throw a parse error with a for loop
  while (headsCounter < success)
    X = rand;
    if(X>0.5)
      headsCounter = headsCounter + 1;
    end
    tries = tries + 1;
  end
  A(ii) = tries;
  if(A(ii-1)<tries)
    largestTries = tries;
  end

  headsCounter = 0;
  tries = 0;
  ii = ii+1;
end

headsCounter
tries
B = A(2:length(A))
hist(B)
xlabel("Number of Tosses")
ylabel("Percentage of Sucess")
title("Negative Binomial Distribution")
octave octave-gui
1个回答
0
投票

我从头开始。无论如何,为了使直方图看起来像它,我应该创建一个从 min(A) 到 max(A) 的新变量箱,通过添加它,它就可以简单地工作。 我还清理了我的代码,这个文本框很奇怪,不允许我像以前一样输入我的代码。

numTrials = 1000
A = zeros(1, numTrials);
p = 0.5 %probability of success
success = 4`
for(ii = 1:numTrials)
numHeads = 0;
numFlips = 0;
while(numHeads<success)
flip = rand;
numFlips = numFlips+1;
if(p>=flip)
numHeads = numHeads+1
end
end
A(ii) = numFlips;
end
bin = (min(A):max(A));
hist(A,bin,1) % 1 for normalized distribution

这完美地绘制了直方图。

© www.soinside.com 2019 - 2024. All rights reserved.