replace code duplication with new invert_matrix method