![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/834310/image.png)
Why does Matlab put symbols out of order when using a matrix?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2021-12-14
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).
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/834310/image.png)
As for why it might do this, that form could be easier for the algorithms in the toolbox to work with.
2 个评论
Walter Roberson
2021-12-15
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
2021-12-15
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Assumptions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!