Writing a script to generarte m random outcomes of a Binomial Random Variable

707 Views Asked by At

I am brand new to Octave and am trying to become familiar with writing code to simulate random events. How could I write a script that generates $m$ outcomes ffrom the CDF of a binomial random variable $X = Bi(5, 0.2)$, for example?

Here is what I have tried so far:

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

  x=zeros(1:m);
  for i = 1:m
    successes = 0;
    for j = 1:n
      u = rand;
      if (u <= p)
        successes++;
      endif
    end
    x(i) = successes;
  end
end

So to simulate 100 random outcomes, I would call generate_bi(5, 0.2, 100)