implemented caching for matrix inversion