Problem with generating random dice rolls
조회 수: 5 (최근 30일)
이전 댓글 표시
I'm trying to display a vector which shows the probabilty of scoring a total score between 2 - 12 from a certain amount of 2 dice rolls. I know I don't need to use ifs and elseifs but it's in the question. The greatest probability should be for a score of 7, yet I'm not getting it.
n2= 0;
n3 = 0;
n4 = 0;
n5 = 0;
n6 = 0;
n7 = 0;
n8 = 0;
n9 = 0;
n10 = 0;
n11 = 0;
n12 = 0;
a = 0;
while (a <= 499)
a = a + 1;
D = randi(12, 1, 2);
if (D(1) + D(2) == 2)
n2 = n2 + 1;
elseif (D(1) + D(2) == 3)
n3 = n3 + 1;
elseif (D(1) + D(2) == 4)
n4 = n4 + 1;
elseif (D(1) + D(2) == 5)
n5 = n5 + 1;
elseif (D(1) + D(2) == 6)
n6 = n6 + 1;
elseif (D(1) + D(2) == 7)
n7 = n7 + 1;
elseif (D(1) + D(2) == 8)
n8 = n8 + 1;
elseif (D(1) + D(2) == 9)
n9 = n9 + 1;
elseif (D(1) + D(2) == 10)
n10 = n10 + 1;
elseif (D(1) + D(2) == 11)
n11 = n11 + 1;
elseif (D(1) + D(2) == 12)
n12 = n12 + 1;
end
end
A = [n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12] * (36/500)
댓글 수: 0
채택된 답변
Image Analyst
2013년 10월 28일
You need to learn how to vectorize! Try this:
numberOfExperiments = 400;
numberOfDice = 2;
rollValues = randi(6, [numberOfDice, numberOfExperiments]);
sumOfRolls = sum(rollValues, 1);
edges = 1:12;
% Get number of each possible sum:
counts = histc(sumOfRolls, edges)
% Convert to percentage.
counts = 100 * counts / sum(counts)
댓글 수: 2
Image Analyst
2013년 10월 28일
It generates random numbers from 1 to the first argument (6). The second argument is the array size. I had two rows where row 1 is the first die, and row 2 is the second die. I have 400 columns, where each column is one throw of the pair of dice. If you like my solution, Please officially mark it as Accepted.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!