My function called RollDice simulates the rolling of a given number of six sided dice a given number of times. The function has 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.
This is my code right now: how do I account for the SUM of the dice? Thanks!
function SumDice= RollDice(NumDice,NumRolls)
FACES= 6;
maxOut= FACES*NumDice;
count= zeros(1,maxOut);
for i = 1:NumRolls
outcome= 0;
for k= 1:NumDice
outcome= outcome + ceil(ranNumDice(1)*FACES);
end
count(outcome)= count(outcome) + 1;
end
bar(NumDice:maxOut, count(NumDice:length(count)));
message= sprintf('% NumDice rolls of % NumDice fair dice', NumRolls, NumDice);
title(message);
xlabel('sum of dice values'); ylabel('Count');
This is a simple and neat little problem (+1) and I enjoyed looking into it :-)
There were quite a few areas where I felt I could improve on your function. Rather than going through them one by one, I thought I'd just re-write the function how I'd do it, and we could go from there. I've written it as a script, but it can be turned into a function easily enough. Finally, I also generalized it a bit by allowing for the dice to have any number of faces (6 or otherwise). So, here it is:
I suggest you have a close look at my code and the documentation for each function I've used. The exercise may prove useful for you when tackling other problems in Matlab in the future. Once you've done that, if there is anything you don't understand, then please let me know in a comment and I'll try to help. Cheers!
ps, If you don't ever need to refer to the individual rolls again, you can of course convert the
AllRoll
andSumRoll
line into a one-liner, ie:SumRoll = sum(randi(NumFace, NumRoll, NumDice), 2);
. I think the two-liner is more readable personally, and I doubt it will make much difference to the efficiency of the code.