# Factorize expression into matrix/vector operations if possible

I'd like to let MMA factorize an expression (tensor) into matrix operations if that's possible.

Example – there's an expression P1 and I want MMA to create another expression P2 such that P1 and P2 are equivalent and P2 can be expressed using matrices, vectors and operations among them;

F   = Array[f, {3, 3}];
Psi = 0.5*mu*(Tr[Transpose[F].F] - 3) - mu*Log[Det[F]] + 0.5*lambda*Log[Det[F]]^2;
P1  = D[Psi, {F}]; (* How to factorize P1 into matrix/vector operations? *)


When we take a look at P1, we can see that each element of P1 is complicated fraction containing many terms. By analyzing P1 one could deduce equivalent notation (P2), which uses only operations between mu, lambda and F and doesn't access individual elements of F:

P2 = mu*(F - Transpose[Inverse[F]]) + lambda*Log[Det[F]]*Transpose[Inverse[F]];

(P1 - P2) // FullSimplify  (* Zero-list => P1 = P2 *)


Can MMA automatically find such P2 for me?

I just wrote a package to do matrix differentiation to answer question (138708). The package can be obtained from:

PacletInstall[file]


to install the package. Then, load the package with:

<<MatrixD


Using MatrixD I get:

MatrixD[.5*mu*(Tr[Transpose[F].F]-3)-mu*Log[Det[F]]+0.5*lambda*Log[Det[F]]^2,F]

(*
0. + 1. F mu - mu Inverse[Transpose[F]] +
1. lambda Inverse[Transpose[F]] Log[Det[F]]
*)
`