with updated code to handle matrix inversion