# Not sure why my code results in a wrong figure. I am trying to simulate 2 dice rolls and counting how many times it takes to roll 2 6s out 10000 trials.

1 view (last 30 days)
Enkhdul Batkhuyag on 28 Apr 2020
num_trial=10000;
num_until_success=1;
counter=[];
success_count=0;
for i=1:num_trial
success_count=0;
num_until_success=0;
while success_count==0
roll_1=randi(6,1);
roll_2=randi(6,1);
num_until_success=num_until_success + 1;
if roll_1==6 && roll_2==6
success_count=1;
end
end
end
histogram(success_count,10);
xlabel('Number of consecutive rolls until two 6s')
ylabel('Number of occurences')
##### 2 CommentsShow NoneHide None
Enkhdul Batkhuyag on 28 Apr 2020
I want to simulate a Monte-carlo simulation and count how many occurences of 2 6s with the the number of rolls to get said success of 2 6s. I tried messing with my code and i can get the number of rolls until 2 6s but the occurence count is fixed at one.
num_trial=10000; % number of trials
num_until_success=1;% number of rolls until 2 6s
counter=[]; % number of consecutive rolls
success_count=0; % counts number of succesful 2 6s
for i=1:num_trial %initializes the for loop
success_count=0;%starts the success count at 0
num_until_success=0; %re-initilize the count before the while loop
while success_count==0 %sets the inequality for the while loop
roll_1=randi(6,1); %simulates one dice rolling
roll_2=randi(6,1); % simulates the second dice rolling
num_until_success=num_until_success + 1; %adds to the variable for each loop thats is unsuccesful
if roll_1==6 && roll_2==6 %sets an if statement and checks that both rolls were 6 via an inequality
success_count=1; %adds to the count if the if statments is true
else
success_count=0;
end
end
end
histogram(num_until_success,10); %plots histogram with 10 bins
xlabel('Number of consecutive rolls until two 6s') % x-axis label
ylabel('Number of occurences') % y-axis label
Enkhdul Batkhuyag on 28 Apr 2020
This the figure I get from my code but the Y-axis is fixed to one and doesn't track the number of occurences per number of rolls until 2 6s

Mrutyunjaya Hiremath on 28 Apr 2020
Hello Enkhdul Batkhuyag,
Try this one -
num_trial=10000;
num_until_success=0;
for i=1:num_trial,i
roll_1=randi(6,1);roll_1
roll_2=randi(6,1);roll_2
if roll_1==6 && roll_2==6
num_until_success=num_until_success + 1;
end
end
disp(num_until_success)
Enkhdul Batkhuyag on 28 Apr 2020
Can you explain what was wrong on my original code, I think it was regarding the counter, as i was trying to plot a scalar and hence the one bar graph but im not exactly clear on how i should have set the for and while loop. Thank you both
Mrutyunjaya Hiremath on 28 Apr 2020
@ James Tursa
Agreed. :)

### Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!