Improve logic for the matrix