# 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.

조회 수: 33(최근 30일)
Baila 2022년 9월 25일
댓글: William Rose 2022년 9월 25일
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 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.
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

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 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.

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

### 범주

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by