Creating a random game of dice
35 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
AJ von Alt
on 20 Jan 2014
Edited: AJ von Alt
on 20 Jan 2014
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 Comments
More Answers (1)
Image Analyst
on 20 Jan 2014
Edited: Image Analyst
on 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 Comments
Image Analyst
on 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 .
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!