A new method is presented for performing first-principles molecular-dynamics simulations of systems with variable occupancies. We adopt a matrix representation for the one-particle statistical operator <(Gamma)over cap> to introduce a ''projected'' free energy functional G that depends on the Kohn-Sham orbitals only and that is invariant under their unitary transformations. The Liouville equation [<(Gamma)over cap>, (H) over cap] = 0 is always satisfied, guaranteeing a very efficient and robust variational minimization algorithm, that can also be extended to nonconventional entropic formulations.