Updated code with matrix caching functionality and comments