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?

 采纳的回答

"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 个评论

What does
ans =
0 1
mean? Does it mean, the first dimension is the same, but the second is not?
"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.
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2019a

标签

Community Treasure Hunt

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

Start Hunting!

Translated by