Counting the number 6s rolled from a dice

29 ビュー (過去 30 日間)
Nathan
Nathan 2025 年 10 月 16 日 12:53
編集済み: Torsten 2025 年 10 月 16 日 19:37
I was trying to get my code to count the number of 6s rolled from 1000 attempts from a dice however it keeps saying it has not rolled a single 6.
X= floor(rand(1,1000)*6)+1;
if X==6
y = y + 1
end
y
>> Week3Q1
y =
0
Why does it display 0 even though a 6 must have been rolled? Help would be appreciated.

採用された回答

Dyuman Joshi
Dyuman Joshi 2025 年 10 月 16 日 13:01
編集済み: Dyuman Joshi 2025 年 10 月 16 日 13:03
You can also use randi to generate the data as well -
X = randi([1 6], 1, 1000);
The "if" statement is only executed when all of the inputs are true -
if [true false]
disp('Hey')
elseif [true true true]
disp('Hello')
end
Hello
What you want to do is to go through each value in X and compare it to 6 -
y = 0;
for k=1:numel(X)
if X(k)==6
y = y+1;
end
end
y
y = 183
You can also do it directly like this -
Y = sum(X==6)
Y = 183
%or
Y = nnz(X==6)
Y = 183
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2025 年 10 月 16 日 13:16
Glad to have helped!
Torsten
Torsten 2025 年 10 月 16 日 19:36
編集済み: Torsten 2025 年 10 月 16 日 19:37
If you want to use "rand" to simulate your experiment, you can interprete the event that "rand" gives a value in between 5/6 and 1 as a "six" for the dice roll.
rng("default")
X = rand(1,10000);
n = nnz(X >= 5/6);
n/10000
ans = 0.1639
1/6
ans = 0.1667

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2025a

Community Treasure Hunt

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

Start Hunting!

Translated by