Not equal operator not working on matrix size
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gergely Takáts
am 24 Mai 2019
Kommentiert: Rik
am 24 Mai 2019
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?
0 Kommentare
Akzeptierte Antwort
Stephen23
am 24 Mai 2019
Bearbeitet: Stephen23
am 24 Mai 2019
"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 Kommentare
Stephen23
am 24 Mai 2019
Bearbeitet: Stephen23
am 24 Mai 2019
"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
am 24 Mai 2019
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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Numeric Types finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!