Symbolic expression flips sign
    4 views (last 30 days)
  
       Show older comments
    
I type a simple symbolic expression and the sign flips for no reason.  It seems to do this only when negative signs are involved.  
syms a
x=5;
z=(x-a)^2;
z=
(a-5)^2
0 Comments
Answers (1)
  Walter Roberson
      
      
 on 18 Feb 2021
        
      Edited: Walter Roberson
      
      
 on 18 Feb 2021
  
      Is there any case where the expression it uses is wrong?
(P*x - P*a)^2 
(P*(x-a))^2
P^2 * (x-a)^2
let P = -1 then P^2 = 1 so
((-1)*x - (-1)*a)^2 
= (x-a)^2
but the first expression is (-x--a)^2 which is (-x+a)^2 which is (a-x)^2
Therefore (a-x)^2 = (x-a)^2
So MATLAB is not wrong.
You might wonder why it bothers to do this. The answer is that 5-a is not represented as _minus(5,a) and is instead represented as _plus(5,_times(-1, a)). When matlab orders commutative expressions, it orders the ones involving symbolic variables before the constants -- it moves the constants to the end and then combines them if there are multiple constants. So it has _plus(_times(-1,a),5) . However it prefers to use positive symbolic variables so it modifies to _times(-1,_plus(a, -5)). After that it sees the ^2 and wants to move constant numeric factors outside, so _times(_power(-1, 2),_power(_plus(a, -5),2) and the _power(-1,2) gets expanded to 1, so _times(1,_power(_plus(a, -5),2)) and the 1 drops out so _power(_plus(a, -5),2) is the final result and gets displayed as (a-5)^2
Remember that what you get back from MATLAB is the result of a computation, and that in order to process the symbolic expressions efficiently and consistently, it may reorder using distributive and associative laws.
"it prefers to use positive symbolic variables" can result in surprising amounts of rewriting, such as ending up rewriting multiple levels of numerator and denominator. Because in an expression with a mix of variable names and signs, it has obscure internal rules about which variable it is going to prioritize being positive.
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
