Creating a random game of dice
Ältere Kommentare anzeigen
This is what I have to do
disp('You are going to throw a dice and get the total for 5 tries')
de=[0 0 0 0 0]
for de(1,1)=ceil(rand*6);
disp(de(1))
end
And you do the same thing for each try
But it keeps giving me an error
Akzeptierte Antwort
Weitere Antworten (1)
Image Analyst
am 20 Jan. 2014
Bearbeitet: Image Analyst
am 20 Jan. 2014
Why use a for loop when you can use randi():
numberOfThrows = 5;
throws = randi(6, numberOfThrows, 1)
sumOfThrows = sum(throws)
And you can put that into a loop over a million or so, if you want, then histogram the sums and plot it with bar().
% Monte Carlo Experiment.
numberOfThrows = 5;
histogram = zeros(numberOfThrows*6, 1);
numberOfExperiments = 100000;
for rolls = 1 : numberOfExperiments
throws = randi(6, numberOfThrows, 1);
sumOfThrows = sum(throws);
histogram(sumOfThrows) = histogram(sumOfThrows) + 1;
end
bar(histogram);
grid on;
caption = sprintf('Results of %d Experiments of %d Throws Each', ...
numberOfExperiments, numberOfThrows);
title(caption, 'FontSize', 13);
caption = sprintf('Sum of %d Throws', numberOfThrows);
xlabel(caption, 'FontSize', 20);
ylabel('Count', 'FontSize', 20);
2 Kommentare
Riri
am 20 Jan. 2014
Image Analyst
am 21 Jan. 2014
Wow. One line of code to do what you and AJ did in way more than that and you can't understand it? randi() is described in the help. The first argument says what the maximum integer is, which would be 6 in the case of dice. The next two numbers are the number of rows and columns. We just want 5 numbers for 5 dice thrown, so the second argument is 5 and the third one is 1. I hope you can follow that and start learning some very useful MATLAB functions. One call to randi and you can eliminate the for loop completely. The random number functions rand(), randi(), and randn() are three of the most commonly used functions and well worth learning .
Kategorien
Mehr zu Particle & Nuclear Physics finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!