updated code for cached matrix