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 (최근 30일)
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
Enkhdul Batkhuyag
Enkhdul Batkhuyag 2020년 4월 28일
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
Enkhdul Batkhuyag 2020년 4월 28일
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
Mrutyunjaya Hiremath 2020년 4월 28일
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)
  댓글 수: 8
Enkhdul Batkhuyag
Enkhdul Batkhuyag 2020년 4월 28일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by