Refactored matrix code