  We establish a new connection between metric Diophantine approximation and
the parametric geometry of numbers by proving a variational principle
facilitating the computation of the Hausdorff and packing dimensions of many
sets of interest in Diophantine approximation. In particular, we show that the
Hausdorff and packing dimensions of the set of singular $m\times n$ matrices
are both equal to $mn \big(1-\frac1{m+n}\big)$, thus proving a conjecture of
Kadyrov, Kleinbock, Lindenstrauss, and Margulis (preprint 2014) as well as
answering a question of Bugeaud, Cheung, and Chevallier (preprint 2016). We
introduce the notion of a $template$, which generalizes the notion of a $rigid$
$system$ (Roy, 2015) to the setting of matrix approximation. Our main theorem
takes the following form: for any class of templates $\mathcal F$ closed under
finite perturbations, the Hausdorff and packing dimensions of the set of
matrices whose successive minima functions are members of $\mathcal F$ (up to
finite perturbation) can be written as the suprema over $\mathcal F$ of certain
natural functions on the space of templates. Besides implying KKLM's
conjecture, this theorem has many other applications including computing the
Hausdorff and packing dimensions of the set of points witnessing a conjecture
of Starkov (2000), and of the set of points witnessing a conjecture of Schmidt
(1983).
