If, ||, && statements

54 visualizaciones (últimos 30 días)
Dylan Leadbetter
Dylan Leadbetter el 19 de Abr. de 2021
Comentada: Dylan Leadbetter el 20 de Abr. de 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 comentarios
Dylan Leadbetter
Dylan Leadbetter el 19 de Abr. de 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 el 20 de Abr. de 2021
Sorry, i dont understand what you mean by class?

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 19 de Abr. de 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))

Más respuestas (0)

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by