completed code for matrix caching