MATLAB: Not equal operator not working on matrix size

MATLABoperatorssize;

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?

Best Answer

"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.