Not equal operator not working on matrix size

I have the following code:
A = [1,2,3];
B = [4,5,6,7];
if size(A) ~= size(B)
disp("not equal 1")
else
disp("equal 1")
end
if size(A) == size(B)
disp("equal 2")
else
disp("not equal 2")
end
This creates the following output:
equal 1
not equal 2
Why does == work as expected, but ~= doesn't? Did I make a mistake?

 採用された回答

Stephen23
Stephen23 2019 年 5 月 24 日
編集済み: Stephen23 2019 年 5 月 24 日

3 投票

"Why does == work as expected, but ~= doesn't?"
They both work exactly as expected.
"Did I make a mistake?"
The IF documentation clearly states "An expression is true when its result is nonempty and contains only nonzero elements". Take a look at your comparison:
>> size(A)~=size(B)
ans =
0 1
Question: Are both of those values non-zero? Answer: no. Therefore your IF condition will not be considered to be true, and the ELSE part will be evaluated instead.
The trivial solution is to always use all or any (depending on your logic):
>> all(size(A)==size(B))
ans = 0
or even better use isequal because this will also work without error for arrays of any size:
>> isequal(size(A),size(B))
ans = 0
TIP: this is exactly why it is recommended to read the documentation for every operator that you use, no matter how trivial you might think it is. Beginners would avoid a lot of bugs if they did this.

3 件のコメント

Gergely Takáts
Gergely Takáts 2019 年 5 月 24 日
What does
ans =
0 1
mean? Does it mean, the first dimension is the same, but the second is not?
Stephen23
Stephen23 2019 年 5 月 24 日
編集済み: Stephen23 2019 年 5 月 24 日
"Does it mean, the first dimension is the same, but the second is not?"
Yes. The logical equivalence operators are all element-wise, which means that they compare the first elements of each array, then second elements of each array, etc. and return the logical values for each of these comparisons.
The first example in the eq and ne documentation shows that quite clearly.
Rik
Rik 2019 年 5 月 24 日
I would support it if Mathworks decided to throw a warning for a non-scalar input to if. If people want the current behavior, what is wrong with this syntax?
if ~isempty(expr) && all(expr)

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2019a

タグ

質問済み:

2019 年 5 月 24 日

コメント済み:

Rik
2019 年 5 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by