I am writing a simulation to display a negative binomial distribution. I have a code that essentially flips a coin and counts how many times until it gets 4 coins. That count is then thrown into a matrix and the whole process is repeated for as many times as I like. So the matrix should end up looking something like [ 5 9 7 11 6 6 7 8 ...] I want to display on a histogram how many times a number shows up. So if it takes 5 tries to get a flip, and 3 of my experiments all take 5 tries, I want a histogram with a height of 3 at 5.
I have had moderate success with the hist() function, but for whatever reason, the bins aren't aligned with the numbers. Such that the hist begins at 4, then the next begins at 4.8 and the next at 5.6, which makes no sense with my data since there are only integers.
Here is my code. I know I can have more arguments in hist and I can normalize the distribution but I am not worried about that right now. I just want to know how to make a histogram with binwidth intervals of 1 not 0.8 or whatever it might be. Picture of histogram attempt :) Thanks for help. I know Matlab has histogram function, but I am coding in Octave because I am a broke college student.enter image description here
I have scoured the internet, nothing helps.
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")
I started from scratch. Anyways, to make the histogram look like it should I created a new variable bin that would be from min(A) to max(A) and by adding this it just simply works. I also cleaned up my code, a lot. While searching for answers I learned a bunch of new functions, like min() and max() which makes this so much easier. I also didn't realize the explanation for hist(x,binwidth), than binwidth was supposed to be an interval which would have helped.
This plots a histogram perfectly.