Matrix Inverse(Matrix &M) { int dim = M.size(); Matrix CofactorMatrix(dim); Matrix InverseMatrix(dim); for(int l=0;l<dim;l++) CofactorMatrix[l].resize(dim); for(int l=0;l<dim;l++) InverseMatrix[l].resize(dim); for(int i = 0; i < dim; i++) { for(int m = 0; m < dim; m++) { Matrix Cofactor(dim-1); for(int l=0;l<dim-1;l++) Cofactor[l].resize(dim-1); int col=0, row=0; for(int j = 0; j < dim; j++) { if(j != i) { row = 0; for(int k = 0; k < dim; k++) { if (k != m) { Cofactor[row][col] = M[k][j]; row++; } } col++; } } CofactorMatrix[i][m] = ((i+m)%2==1?-1.0:1.0) * Det(Cofactor); } } for(int i=0; i< dim; i++) { InverseMatrix[i] = (1.0/Det(M))*CofactorMatrix[i]; } return InverseMatrix; }
Matrix CramersRuleInverse(const Matrix& mat) { return (CofactorMatrix(mat)).transp()/determinant(mat); }