Clear Filters
Clear Filters

Problem with generating random dice rolls

3 views (last 30 days)
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)

Accepted Answer

Image Analyst
Image Analyst on 28 Oct 2013
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 Comments
Jon
Jon on 28 Oct 2013
Thanks a lot. How does the randi function actually work in this case?
Image Analyst
Image Analyst on 28 Oct 2013
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!