TITLE: 'Trace trick' for expectations of quadratic forms
QUESTION [25 upvotes]: I am trying to understand the proof for the Kullback-Leibler divergence between two multivariate normal distributions. On the way, a sort of trace trick is applied for the expectation of the quadratic form $$E[ (x-\mu)^T \Sigma^{-1} (x-\mu) ]= \operatorname{trace}(E[(x-\mu)(x-\mu)^T)] \Sigma^{-1}),$$
where $x$ is MV-normal with mean $\mu$ and covariance matrix $\Sigma$. The expectation is taken over $x$. 
I would like to understand why this identity holds. I think more than one step is taken at once. I believe, $\operatorname{trace}(E[(x-\mu)(x-\mu)^T] \Sigma^{-1})$ = $\operatorname{trace}(E[(x-\mu) \Sigma^{-1} (x-\mu)^T])$, but where does the trace come from?

REPLY [12 votes]: To add to @angryavian's answer, you can swap expectation and trace because,
$$ tr(E[A]) = 
tr(\begin{bmatrix} E[a_{11}] & \dots & \\
\vdots & E[a_{22}] & \\
& & \ddots\end{bmatrix}) = \sum\limits_{i=1}^N E[a_{ii}]=E[\sum\limits_{i=1}^N a_{ii}] = E[tr(A)] $$