TITLE: Matrix-by-matrix derivative formula
QUESTION [9 upvotes]: I need to derive $\frac{\delta(X^{T}MX)}{\delta X}$, where $X$ and $M$ are $n \times n$ matrices.
I know that $\frac{\delta(AXB)}{\delta X}=B^{T} \otimes A$ but am having a hard time deriving what I need from that or from scratch.

REPLY [7 votes]: Start with a matrix function, then take the differential, then vectorize and identify the gradient.
$$\eqalign{
 F &= X^TMX \cr
dF &= dX^TMX + X^TMdX \cr
{\rm vec}(dF) &= {\rm vec}(dX^TMX) + {\rm vec}(X^TMdX) \cr
df&=(X^TM^T\otimes I){\rm vec}(dX^T) + (I\otimes X^TM){\rm vec}(dX)\cr
&= \Big((X^TM^T\otimes I)K + (I\otimes X^TM)\Big)\,{\rm vec}(dX) \cr
\frac{\partial f}{\partial x} &= (X^TM^T\otimes I)K + (I\otimes X^TM) \cr
}$$
where $K$ is the Commutation Matrix for Kronecker products.