Implemented matrix caching as specified in the assignment.