My code was to create the game tic tac toe and i had to include the character '0' otherwise to would come up with a blank spot in my matrix, not a 0
If, ||, && statements
23 次查看(过去 30 天)
显示 更早的评论
Hi, I was wondering why this bit of code does not work? Im trying to make it so that in a 3x3 matrix, if a row or column or diagonal of 3 is equal to 0, then it prints 'you lose' once.
if Matrix(1,:)=='0'||Matrix(2,:)=='0'||Matrix(3,:)=='0'||Matrix(:,1)=='0'||Matrix(:,2)=='0'||Matrix(:,3)=='0'||(Matrix(1,3)=='0'&&Matrix(2,2)=='0'&&Matrix(3,1)=='0')||(Matrix(1,1)=='0'&&Matrix(2,2)=='0'&&Matrix(3,3)=='0')
fprintf('you lose')
elseif fprintf('its a tie')
end
采纳的回答
Walter Roberson
2021-4-19
if Matrix(1,:)=='0'||Matrix(2,:)=='0'||Matrix(3,:)=='0'||Matrix(:,1)=='0'||Matrix(:,2)=='0'||Matrix(:,3)=='0'||(Matrix(1,3)=='0'&&Matrix(2,2)=='0'&&Matrix(3,1)=='0')||(Matrix(1,1)=='0'&&Matrix(2,2)=='0'&&Matrix(3,3)=='0')
Matrix(1,:) is a vector of 3 values, You are comparing all three values to '0', which will give you back a vector of 3 logical values. You then have a || operator, but || can only be used when the left side evaluates to a scalar, and the right side evaluates to a scalar if the left side is false. You need to use all(), such as
if all(Matrix(1,:)=='0')||all(Matrix(2,:)=='0')||all(Matrix(3,:)=='0')
and so on.
Hint:
mask = Matrix == '0';
any(all(mask,1)) || any(all(mask,2))
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!