Why does Matlab put symbols out of order when using a matrix?

1 次查看(过去 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?

采纳的回答

Steven Lord
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).
As for why it might do this, that form could be easier for the algorithms in the toolbox to work with.
  2 个评论
Walter Roberson
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)
ans = 
Walter Roberson
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
x = 
feval(symengine, 'op', x)
ans = 
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.

请先登录,再进行评论。

更多回答(1 个)

Voss
Voss 2021-12-14
编辑:Voss 2021-12-14
Some math (not MATLAB code):
sin(C-A-B) = -sin(-(C-A-B)) % because sin is an odd function, i.e., sin(-x) = -sin(x)
= -sin(A+B-C)

类别

Help CenterFile Exchange 中查找有关 Assumptions 的更多信息

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by