Why does Matlab put symbols out of order when using a matrix?
1 view (last 30 days)
Show older comments
Sergio Diaz
on 14 Dec 2021
Commented: Walter Roberson
on 15 Dec 2021
I have the following code:
syms A B C;
vars = [A, B, C];
y(vars(1), vars(2), vars(3)) = sin(vars(3) - vars(1) - vars(2));
When I check my workspace, y equals the following:
-sin(A + B - C)
WHAT????? That makes no sense at all. No clue what to even ask on this question besides what is going wrong?
0 Comments
Accepted Answer
Steven Lord
on 14 Dec 2021
Symbolic Math Toolbox is allowed to replace one expression with another if they are equivalent. Because of the reflection identity that states that it is allowed to replace sin(C-B-A) with -sin(-C+B+A) and since addition is commutative it can rewrite that as -sin(A+B-C).
As for why it might do this, that form could be easier for the algorithms in the toolbox to work with.
2 Comments
Walter Roberson
on 15 Dec 2021
The rules are not immediately obvious, except that we can see that symbolic toolbox prefers to have a leading positive coefficient.
The rule kind of looks like "use alphabetical order, but move the first positive coefficient to be first in the chain" -- but that does not explain c - b - a + d
syms a b c d
vars = [a b c d];
sum(perms(vars) .* [1 -1 1 -1],2)
Walter Roberson
on 15 Dec 2021
There is a difference between the rules for internal representation, and the rules for display.
syms a b c d
x = -a - b + c + d
feval(symengine, 'op', x)
Internally it has arranged the terms in alphabetical order, but for printing it is using a different order.
The reason to rearrange terms internally is that the symbolic engine avoids keeping full copies of every expression. Instead, each time it computes a sub-expression, it looks to see if that sub-expression already exists inside the symbolic engine, and if so replaces the sub-expression with the pointer to the other version of it. The run-time of checking to see if expressions (written in terms of the same operations) are equal is exponential unless you cannonicalize the expression order -- and if you do cannonicalize it then the checking can be done through a hash table lookup.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!