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 件のコメント

Dylan Leadbetter
Dylan Leadbetter 2021 年 4 月 19 日
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 2021 年 4 月 20 日
Sorry, i dont understand what you mean by class?

サインインしてコメントする。

 採用された回答

Walter Roberson
Walter Roberson 2021 年 4 月 19 日

0 投票

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 件)

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by