I'd like to simplify a complex symbolic expression expr
by substituting and listing subexpressions that appear more than once in expr
– kind of like Matlab does.
I need to port the result to C code, so the motivation is avoiding unnecessary recomputation of subterms.
To illustrate the idea, let's pick a simple expression expr = Inverse[Array[a, {2,2}]]
:
Actual output of MMA when executing Inverse[Array[a, {3,3}]]
:
$$ \left( \begin{array}{cc} \frac{a(2,2)}{a(1,1) a(2,2)-a(1,2) a(2,1)} & -\frac{a(1,2)}{a(1,1) a(2,2)-a(1,2) a(2,1)} \\ -\frac{a(2,1)}{a(1,1) a(2,2)-a(1,2) a(2,1)} & \frac{a(1,1)}{a(1,1) a(2,2)-a(1,2) a(2,1)} \\ \end{array} \right) $$
By looking at the output of this simple expression, I can see that the denominator is exactly the same in all of the matrix's elements (the determinant of the matrix).
The desired output of MMA: $$ \left( \begin{array}{cc} \frac{a(2,2)}{S_1} & -\frac{a(1,2)}{S_1} \\ -\frac{a(2,1)}{S_1} & \frac{a(1,1)}{S_1} \\ \end{array} \right), $$
Where:
$$S_1 = a(1,1) a(2,2)-a(1,2) a(2,1)$$
Inverse[Array[a, {2, 2}]] /. {-a[1, 2] a[2, 1] + a[1, 1] a[2, 2] -> S1}
$\endgroup$Experimental`OptimizeExpression[Inverse[Array[a, {2, 2}]]]
. $\endgroup$expr
(in my caseexpr
is composed of operations on 6x6 matrices). $\endgroup$Experimental`OptimizeExpression
? $\endgroup$