# Expand tensor expressions with matrix powers and outer products

I would like to have TensorExpand distribute across repeated matrices involving outer products. This question notes that TensorExpand has a problem with expressions of a matrix raised to a power greater than one:

$Assumptions = u \[Element] Vectors[m, Reals] && A \[Element] Matrices[{m, m}, Reals] && B \[Element] Matrices[{m, m}, Reals]; TensorExpand[u . (A) . (A) .u ]  yields an expression involving MatrixProduct, u.MatrixPower[A, 2].u, whereas TensorExpand[u . (A) . (B) .u ]  simply yields u.A.B.u. The solution proposed by @Szabolcs is to use Distribute: Distribute[u . (A) . (A) .u ]  yields u.A.A.u. However, this doesn't work if the matrices in the quadratic form involve outer products: Idm = IdentityMatrix[m]; Distribute[ u . (Idm + u\[TensorProduct]u) . (Idm + u\[TensorProduct]u) .u ]  yields u.u + 2 (u.u)^2 + u.MatrixPower[u\[TensorProduct]u, 2].u and just plain Distribute doesn't simplify the outer products. How can I avoid this behavior? I.e, have the above evaluate to u.u + 2 (u.u)^2 + (u.u)^3? ## 1 Answer You could make use of the ResourceFunction objects "FromTensor" and "ToTensor": Idm=IdentityMatrix[m]; t = u . (Idm+u\[TensorProduct]u) . (Idm+u\[TensorProduct]u) . u;$Assumptions = u ∈ Vectors[{m}];

TensorReduce @ ResourceFunction["FromTensor"] @ ResourceFunction["ToTensor"] @ t


u . u + 2 (u . u)^2 + (u . u)^3

• Is there a reason this would be preferable to something like Distribute[ u . (Idm +\[TensorProduct]u) . (Idm * c + u\[TensorProduct]u) .u ] /. c->1, which is the hacky solution I ended up using? I.e., making the repeated elements different by introducing a scalar and later getting rid of it? I don't have a good sense of what is and isn't a kludgy solution in Mathematica since algorithms for symbolic math tend to involve a bunch of heuristics / ad hoc tricks... Dec 9, 2021 at 20:04