Creating a random game of dice
35 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
AJ von Alt
2014-1-20
编辑:AJ von Alt
2014-1-20
A for loop needs an index variable and a set of values to loop through. Check out the documentation here. It has the form:
for index = values
program statements
:
end
I suspect you mean to do something like this:
disp('You are going to throw a dice and get the total for 5 tries')
de=[0 0 0 0 0]
for i = 1:6;
de(i) = ??? % your code here
disp( de(i) )
end
Pay careful attention to the de(i) syntax. We use de(i) instead of de(1), so that in the first run through of the loop we are working with de(1), in the second run through we get de(2) and so on all the way up to de(6).
0 个评论
更多回答(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 个评论
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 .
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!