Finding the dimension of $S = \{B \in M_n \,|\, AB = BA\}$, where $A$ is a diagonalizable matrix

Hint: Write $D$ as a block matrix $$ D= \pmatrix{ \lambda_1 I \\ & \lambda_2 I \\ && \ddots \\ &&& \lambda_k I } $$ Noting that $$ P^{-1}[AB]P= D(P^{-1} BP), \qquad P^{-1}[BA]P= (P^{-1} BP)D $$ It suffices to determine which matrices $M$ satisfy $MD=DM$.

To that end, write $M$ as a block matrix (partitioned in the same way as $D$), and compute the products $DM$ and $MD$. Determine that all blocks of $M$ must be zero except those on the diagonal.


Hint. Let $B = [b_{ij}]$ be a $n\times n$ matrix which commutes with a diagonal matrix $D=\mbox{diag}(\lambda_1,\lambda_2,\dots,\lambda_n)$, that is $DB=BD$.

Then by computing $DB$ and $BD$, we get that for all $1\leq i,j\leq n$, $$\lambda_i b_{ij} = b_{ij}\lambda_j$$ which implies that $(\lambda_i - \lambda_j) b_{ij} = 0$. Hence either $\lambda_i = \lambda_j$ or $b_{ij} = 0$.