If, ||, && statements

61 views (last 30 days)
Dylan Leadbetter
Dylan Leadbetter on 19 Apr 2021
Commented: Dylan Leadbetter on 20 Apr 2021
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
  2 Comments
Dylan Leadbetter
Dylan Leadbetter on 19 Apr 2021
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
Dylan Leadbetter
Dylan Leadbetter on 20 Apr 2021
Sorry, i dont understand what you mean by class?

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 19 Apr 2021
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))

More Answers (0)

Categories

Find more on Just for fun in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!