필터 지우기
필터 지우기

Multiple Dice Rolls Help

조회 수: 3 (최근 30일)
SB
SB 2012년 11월 21일
댓글: nazar youssef 2017년 11월 15일
So basically, I have to write a function that simulates the rolling of a
given number of six sided dice a given number of times. The function should
take
two input arguments, the number of dice (NumDice) that will be rolled in each
experiment and the total number (NumRolls) of times that the dice will be
rolled. The output of the function will be a vector SumDice of length NumRolls
that contains the sum of the dice values in each experiment. I'll have to make
a histogram afterwards (which I havent done yet)
Here's what I've got so far, not sure how to make it a sum of dice:
% function SumDice=RollDice(NumDice,NumRolls)
distribution=zeros(6,1);
for roll=1:NumRolls
diceValues = randi(6,[NumDice 1]);
for die = 1 : NumDice
distribution(diceValues(die)) = distribution(diceValues(die)) +1;
end
end

채택된 답변

Walter Roberson
Walter Roberson 2012년 11월 21일
Sum of dice is just sum(diceValues). And you will not need the "for die" loop as you only get a single sum.
(By the way, the entire function can be done as a single expression, including the histogram.)
  댓글 수: 4
SB
SB 2012년 11월 21일
Could you maybe show an example? Vectorizing the summation as in within a vector using recursion or something?
Walter Roberson
Walter Roberson 2012년 11월 21일
sum() can be applied to arrays, not just to vectors.

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

추가 답변 (1개)

Harshit
Harshit 2012년 11월 21일
Here is what I feel will work fine
% function SumDice=RollDice(NumDice,NumRolls)
distribution=zeros(NumDice*6,1);
for roll=1:NumRolls
diceValues = randi(6,[NumDice 1]);
totaldiceValue = sum(diceValues);
distribution(totaldiceValue) = distribution(totaldiceValue) +1;
end
end
  댓글 수: 1
nazar youssef
nazar youssef 2017년 11월 15일
how to call the function?

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

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by