How to get the gradient of the trace of a matrix? Like the one I formulate below,
$\pi \in \mathbb{R}^n$ 
$$\frac{\partial \text{trace}\left((X^T\text{diag}(\pi)X)^{-1}\right)}{\partial \pi} = ?$$
I tried to derive,
\begin{align*}
\text{trace}\left((X^T\text{diag}(\pi)X)^{-1}\right) \\
= \text{trace}\left(\left(\text{diag}(\pi)X\right)^{-1}X^{-T}\right) \\
= \text{trace}\left(X^{-1}\text{diag}(\frac{1}{\pi})X^{-T}\right) \\
= \sum_i\sum_jX^{-1}_{ij}\frac{1}{\pi_j}X^{-T}_{ji} \\
\frac{\partial \sum_i\sum_jX^{-1}_{ij}\frac{1}{\pi_j}X^{-T}_{ji}}{\partial \pi} = X^{-1}\odot X^{-T}\mathbf{1} \frac{\partial 1/\pi}{\partial \pi}\\
= -\frac{1}{\pi^2}X^{-1}\odot X^{-T} \mathbf{1}\\
= -\frac{1}{\pi^2}\text{trace}(X^{-T}X^{-T}) \mathbf{1}
\end{align*}    
Am I right with my derivation?
 A: For ease of typing, let $$P=\operatorname{Diag}(\pi)$$
Also, let's define the symmetric matrix $$M=X^TPX$$
Rewrite the function in terms of this new variable and find its differential and gradient
$$\eqalign{
  f &= \operatorname{tr}(M^{-1}) \cr\cr
 df &= -M^{-2}:dM \cr
    &= -M^{-2}:X^T\,dP\,X \cr
    &= -XM^{-2}X^T:dP \cr
    &= -XM^{-2}X^T:\operatorname{Diag}(d\pi) \cr
    &= -\operatorname{diag}(XM^{-2}X^T):d\pi \cr\cr
\frac{\partial f}{\partial\pi} &= -\operatorname{diag}(XM^{-2}X^T) \cr
    &= -\operatorname{diag}\Big(X\big(X^T\operatorname{Diag}(\pi\big)X)^{-2}X^T\Big) \cr
}$$
where I've used the notations:
$\operatorname{Diag}(a)$ to generate a diagonal matrix from a vector, 
$\operatorname{diag}(A)$ to return the diagonal of a matrix as a vector,
and colons to represent the the Frobenius inner product.
A: I suppose $\pi$ is an $n$-vector. Let $Y=(XX^T)^{-1}$. The trace is then $\sum_{k=1}^n \dfrac{y_{kk}}{\pi_k}$. It should be easy to find its partial derivative with respect to each $\pi_i$.
If $\pi$ is an $n\times n$ matrix, do the similar stuffs. The trace is $\sum_{k=1}^n \dfrac{y_{kk}}{\pi_{kk}}$ and it is straightforward to evaluate its partial derivative with respect to each $\pi_{ij}$.
