Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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?

Akzeptierte Antwort

Steven Lord
Steven Lord am 14 Dez. 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 Kommentare
Walter Roberson
Walter Roberson am 15 Dez. 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)
ans = 
Walter Roberson
Walter Roberson am 15 Dez. 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
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Voss
Voss am 14 Dez. 2021
Bearbeitet: Voss am 14 Dez. 2021
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)

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by