Counting the number of occurences in an array

3 ビュー (過去 30 日間)
Gina Barlage
Gina Barlage 2015 年 6 月 11 日
回答済み: Image Analyst 2015 年 6 月 11 日
This was my assignment:
The script should roll five dice
(the command randi(6, [1 5]) should prove handy)
and decide if the roll includes three,
four or five of the same number.
Recall the potential use of sort and
diff in answering questions like this,
The script should roll all five dice 100000 times
and produce the following percentages:
- Percentage of rolls achieving five of a kind (Yahtzees)
- Percentage of rolls achieving four of a kind
- Percentage of rolls achieving three of a kind
- Percentage meeting none of the above
This is what I have so far:
tracker = 0;
%for ii = 1 : 100000
tracker = tracker + 1;
roll = randi(6, [1 5])
roll_sorted = sort(roll)
difference = diff(roll_sorted)
ctr = 0;
for jj = 1 : 4
if difference(jj) == 0
ctr = ctr + 1;
else
ctr = ctr;
end
end

回答 (1 件)

Image Analyst
Image Analyst 2015 年 6 月 11 日
Why not simply use histcounts() or histogram()? (Or hist() or histc() if you're using an old version of MATLAB?)
And why not do all 100000 rolls at the same time?
allRolls = randi(6, [5, 100000]);

カテゴリ

Help Center および File ExchangeWord games についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by