Create a loop which rolls the dice 100 times, stores the sum of all rolls in a variable and then plots a histogram of the sums.

23 views (last 30 days)
this is my code so far
S = 6;
R = 1;
N = 2;
T = 100;
out = randi([1 S],[R N T]);
I know i am missing a way to store the sum of all rolls.
I have tried multiple things and used many resources so im not sure what to do.
I appreciate any help. Thanks!

Answers (2)

Image Analyst
Image Analyst on 25 Sep 2022
Edited: Image Analyst on 25 Sep 2022
You're not using descriptive variable names. What do they all mean. I guess the badly-named T is numberOfRolls, and S is the maxDieNumber, but what are R and N? And where is the for loop they asked you to do?
thisRoll = zeros(1, numberOfRolls);
for roll = 1 : numberOfRolls
thisRoll(roll) = randi(maxDieNumber, 1, 1) % Roll a single die one time.
% Sum all the rolls.
sumOfAllRolls = sum(thisRoll)
% Now call histogram()
You should be able to complete it.

William Rose
William Rose on 25 Sep 2022
Unlike many post-ers, you have made an attempt, which is laudable.
S = 6;
R = 1;
N = 2;
T = 100;
%out = randi([1 S],[R N T]); %old way
out = randi([1 S],[1 T]); %new way
1 100
You can see that out computed the second way is more compact than out computed the first way.
The histogram is for each of the the 100 rolls. Did you want to put oll this inside a larger loop that does 100 rolls mulitple times? In that case you would need an outer loop, and save the value of sum(out) for each run through the outper loop. (You could actually do it without any loops....)
  1 Comment
William Rose
William Rose on 25 Sep 2022
Note that R and N are not used in the code aove. I am not sure what their purpose is supposed to be. Maybe N is supposed to be the number of sets of 100 rolls, which was implicitly one in the code above. If you want N sets of 100 rolls:
S = 6;
N = 1000; %number of trials
T = 100; %number of rolls per trial
out = randi([1 S],[T, N]);
xlabel('Value of sumout');
ylabel('Number of occurrences')
titlestr=sprintf('N=%d trials',N);
Try it.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!