Is there a way to extract the diagonal from a matrix with simple matrix operations

Note: This solution is not working for the updated question. $$ D = \text{diag}(a_{11}, \ldots, a_{nn}) = \sum_{i=1}^n P_{(i)} A P_{(i)} $$ where $P_{(i)}$ is the projection on the $i$-th coordinate: $$ (P_{(i)})_{jk} = \delta_{ij} \delta_{jk} \quad (i,j,k \in \{1,\ldots,n\}) $$ and $\delta$ is the Kronecker delta ($1$ for same index values, otherwise $0$).

Transforming the diagonal matrix $D$ into a row vector can be done by $$ d = u^T D $$ where each of the $n$ components of $u$ is $1$. $$ u = (1,1,\ldots,1)^T $$ Combining both gives $$ d = \sum_i u^T P_{(i)} A P_{(i)} = \sum_i e_i^T A P_{(i)} $$ where $e_i$ is the $i$-th canonical base vector.

Example:

octave> A, P1, P2, u
A =
   1   2
   3   4

P1 =
   1   0
   0   0

P2 =
   0   0
   0   1

u =
   1
   1

octave> u'*(P1*A*P1+P2*A*P2)
ans =
   1   4

Tags:

Matrices