Geometry optimization and electronic properties of BMgn, AlMgn(n=1—12) clusters have been studied based on density functional theory (DFT). With the increase of the number of Mg atoms, the boron atom gradually comes into the interior of the Mgn cluster. However, the growth patterns of AlMgn clusters are similar to that of magnesium clusters. Doping of a B or Al atom makes the average binding energy higher and the stability enhanced. The atomic configuration plays a dominant role in the stability of B, Al atom doped magnesium clusters. The induction of B, Al atoms makes the NBO charge population of host magnesium clusters obviously altered. The peak of the average NBO charges population of 3p orbital of Mg atoms in AlMgn clusters is in agreement with the stability of AlMgn (n=1—12) clusters.