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.

조회 수: 36 (최근 30일)
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!

답변 (2개)

Image Analyst
Image Analyst 2022년 9월 25일
편집: Image Analyst 2022년 9월 25일
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 2022년 9월 25일
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
William Rose
William Rose 2022년 9월 25일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by