Refactor Matrices code