code for calculating and caching matrix added