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.

32 Ansichten (letzte 30 Tage)
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!

Antworten (2)

Image Analyst
Image Analyst am 25 Sep. 2022
Bearbeitet: Image Analyst am 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.
end
% Sum all the rolls.
sumOfAllRolls = sum(thisRoll)
% Now call histogram()
You should be able to complete it.

William Rose
William Rose am 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
%disp(size(out))
out = randi([1 S],[1 T]); %new way
sumout=sum(out);
fprintf('Sum(out)=%d.\n',sumout)
Sum(out)=338.
disp(size(out))
1 100
histogram(out)
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 Kommentar
William Rose
William Rose am 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]);
sumout=sum(out);
fprintf('Mean(Sum(out))=%.1f.\n',mean(sumout))
Mean(Sum(out))=349.6.
histogram(sumout)
xlabel('Value of sumout');
ylabel('Number of occurrences')
titlestr=sprintf('N=%d trials',N);
title(titlestr)
Try it.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Graphics Performance finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by