modified code for cachematrix