Made matrix dimensions dynamic and validated