フィルターのクリア

Dice roll, how to write if statement for not 6 or 1?

1 回表示 (過去 30 日間)
Matthew Lozancich
Matthew Lozancich 2017 年 11 月 23 日
コメント済み: Matthew Lozancich 2017 年 11 月 24 日
So for rolling dice:
x=randi([1,6],1,2);
How do I write an if statement for the conditions that both dice (x(1) and x(2)) are not a 6 or 1. I did:
if x(1)~=6
if x(1)~=1
if x(2)~=1
if x(2) ~= 1
winnings=winnings+1
end
end
end
end
But this is really ugly..

採用された回答

Jan
Jan 2017 年 11 月 23 日
編集済み: Jan 2017 年 11 月 23 日
if any(x(1) == 2:5) && any(x(2) == 2:5)
winnings = winnings + 1;
end
You can do this in 1 line also:
winnings = winnings + (any(x(1) == 2:5) && any(x(2) == 2:5));
Or
winnings = winnings + all(ismember(x, 2:5));
Or you can use min and max:
winnings = winnings + (min(x) > 1 && max(x) < 6);
A look up table works also:
LUT = [0, 1, 1, 1, 1, 1, 0]; % Elements 1 and 6 are 0
winnings = winnings + all(LUT(x));

その他の回答 (1 件)

James Tursa
James Tursa 2017 年 11 月 23 日
編集済み: James Tursa 2017 年 11 月 23 日
E.g.,
if all(ismember(x,2:5))

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by