Home > Mobile >  Why does MATLAB fail to check the equality of this trigonometric expression
Why does MATLAB fail to check the equality of this trigonometric expression

Time:01-20

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?

CodePudding user response:

At the bottom of the documentation page, there is a section called "Tips", which contains the following item:

isequaln(A,B) checks if A and B are the same size and their contents are syntactically the same expression, treating NaN values as equal. To check whether the mathematical comparison A == B holds for all values of variables in A and B, use isAlways(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
  •  Tags:  
  • Related