Solution (source code)

= Solution

If $Mv=\lambda v$ for a nonzero <eigenvector>, then $M^2=M$ implies $(\lambda^2-\lambda)v=0$, hence $\lambda\in\{0,1\}$. Conversely, the real-symmetric <spectral theorem> gives $M=Q\Lambda Q^T$ with orthogonal $Q$. If every diagonal entry of $\Lambda$ is zero or one, then $\Lambda^2=\Lambda$ and therefore $M^2=M$. Thus the necessary and sufficient condition is
$$
\boxed{\text{Every eigenvalue of }M\text{ is either }0\text{ or }1.}
$$
Such a symmetric <idempotent matrix> is the <orthogonal projection> onto its eigenvalue-one <eigenspace>, with its eigenvalue-zero <eigenspace> as the kernel. Diagonalizability is essential to the sufficiency argument from eigenvalues alone; symmetry supplies it here.