フィルターのクリア

Problem with generating random dice rolls

3 ビュー (過去 30 日間)
Jon
Jon 2013 年 10 月 28 日
コメント済み: Image Analyst 2013 年 10 月 28 日
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)

採用された回答

Image Analyst
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 件のコメント
Jon
Jon 2013 年 10 月 28 日
Thanks a lot. How does the randi function actually work in this case?
Image Analyst
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 ExchangeGet Started with MATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by