Creating a random game of dice
古いコメントを表示
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
採用された回答
その他の回答 (1 件)
Image Analyst
2014 年 1 月 20 日
編集済み: Image Analyst
2014 年 1 月 20 日
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 件のコメント
Riri
2014 年 1 月 20 日
Image Analyst
2014 年 1 月 21 日
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 .
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!