Why does MATLAB fail to check the equality of this trigonometric expression
isequaln()
is testing symbolic objects for equality as stated in the documentation. However, this is not the case with the following script.
syms a
f1=cos(a)^2;
f2=1-sin(a)^2;
isequaln(f1,f2)
ans =
logical
0
MATLAB does not return the correct answer. What does MATLAB do when comparing equality for symbolic expressions, compare strings (i.e. a typical scenario for regular expressions), or something else?
At the bottom of the documentation page, there is a section called "Tips", which contains the following item:
isequaln(A,B)
checks ifA
andB
are the same size and their contents are syntactically the same expression, treating NaN values as equal. To check whether the mathematical comparisonA == B
holds for all values of variables inA
andB
, useisAlways(A == B)
.
(emphasis mine)
isAlways
does what you want:
syms a
f1 = cos(a)^2;
f2 = 1-sin(a)^2;
isAlways(f1 == f2)
This outputs true
.
Alternatives:
>> simplify(f1-f2)
ans =
0
>> simplify(f1==f2)
ans =
symtrue