Added code to calculate a matrix or return cached version