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
16 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dylan Leadbetter
am 19 Apr. 2021
Kommentiert: Dylan Leadbetter
am 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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))
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Strategy & Logic finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!