Not equal operator not working on matrix size

조회 수: 4 (최근 30일)
Gergely Takáts
Gergely Takáts 2019년 5월 24일
댓글: Rik 2019년 5월 24일
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일
"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
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개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by