Problem with generating random dice rolls
1 次查看(过去 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 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!