The code generation function detects sub-expressions that occur more than once, and optimizes by creating temporary variables for those. This feature is very useful since it is very common for a function to share expressions with its derivative, or for the derivative to contain repeated expressions.
TomSym automatically implements algebraic simplifications of expressions. Among them are:
- Multiplication by 1 is eliminated: 1*A = A
- Addition/subtraction of 0 is eliminated: 0+A = A
- All-same matrices are reduced to scalars: [3;3;3]+x = 3+x
- Scalars are moved to the left in multiplications: A*y = y*A
- Scalars are moved to the left in addition/subtraction: A-y = -y+A
- Expressions involving element-wise operations are moved inside setdiag: setdiag(A)+setdiag(A) = setdiag(A+A)
- Inverse operations cancel: sqrt(x)^2 = x
- Multiplication by inverse cancels: A*inv(A) = eye(size(A))
- Subtraction of self cancels: A-A = zeros(size(A))
- Among others...