The formation of the nuclei of galaxies. I - M31