refactor matrix inversion