0

我刚刚开始使用 Octave 并试图模拟二项式随机变量的 10,000 个结果,定义为:

X ~ Bi(5, 0.2)

我用以下函数绘制了结果:

function x = generate_binomial_bernoulli(n,p,m)
  % generate Bi(n, p) outcomes m times

  x = zeros(1,m);       % allocate array for m simulations
  for i = 1:m           % iterate over m simulations
    successes = 0;      % count the number of successful trials per simualtion (0-5)
    for j = 1:n         % iterate through the n trials
      u = rand;         % generate random nuumber from 0-1
      if (u <= p)       % if random number is <= p
        successes++;    % count it as a success
      endif
    end
    x(i) = successes;   % store the number of successful trials in this simulation
  end

  alphabet_x=[0:n];     % create an array from 0 to n        
  hist(x,alphabet_x);   % plot graph     

end

然后我用generate_binomial_bernoulli(5, 0.2, 10000).

这是模拟 5 次伯努利试验,每个试验的成功概率为 0.2,重复 5 次试验 10,000 次,并绘制成功次数分布图。该图显示了模拟的经验结果。

在此处输入图像描述

我现在还被要求绘制理论结果,我最好的猜测是在 x 轴(0.2 * 5 = 1)上围绕 1 个成功的正态分布图。

  1. 我怎样才能创建这个图,并将其显示在同一个直方图上?
  2. 我怎样才能正确地显示我的图表,其中 x 轴仅从 0 到 5,两个轴都标有标签,两个直方图用图例进行颜色编码?

编辑

这是我当前尝试绘制归一化/理论曲线的函数:

function x = generate_binomial_bernoulli(n,p,m)
  % generate Bi(n, p) outcomes m times

  emperical = zeros(1,m);             % allocate array for m simulations
  for i = 1:m                         % iterate over m simulations
    successes = 0;                    % count the number of successful trials per simualtion (0-5)
    for j = 1:n                       % iterate through the n trials
      u = rand;                       % generate random nuumber from 0-1
      if (u <= p)                     % if random number is <= p
        successes++;                  % count it as a success
      endif
    end
    emperical(i) = successes;         % store the number of successful trials in this simulation
  end

  close all;                          % close any existing graphs

  x_values = [0:n];                   % array of x-axis values        
  hist(emperical, x_values, "facecolor", "r"); % plot empirical data
  xlim([-0.5 (n + 0.5)]);             % set x-axis to allow for histogram bar widths

  hold on;                            % hold current graph

  mean = n * p;                       % theoretical mean
  norm = normpdf(x_values, mean, 1);  % normalised y values
  plot(x_values, norm, "color", "b"); % plot theoretical distribution

  legend('Emprical', 'Theoretical');   

end

如下图,这条曲线只沿着y轴延伸到一个非常低的高度,但我不知道如何跨越整个数据集。

在此处输入图像描述

4

1 回答 1

0

获取直方图数量和 bin:

[counts,centers] = hist(x);

标准化:

freq = counts/sum(counts);

绘制归一化直方图:

bar(centers,freq)
于 2017-03-22T05:13:07.873 回答