C ++程序查找图矩阵的逆
这是一个C++程序,用于查找图矩阵的逆。仅当矩阵非奇异(即行列式不应该为0)时,才存在矩阵的逆。矩阵的逆可以以许多方式找出。在这里,我们使用伴随矩阵及其行列式找出图矩阵的逆。示例中涉及的步骤
Begin function INV() to get the inverse of the matrix: Call function DET(). Call function ADJ(). Find the inverse of the matrix using the formula; Inverse(matrix) = ADJ(matrix) / DET(matrix) End.
示例
#include<bits/stdc++.h>
using namespace std;
#define N 5
void getCfactor(int M[N][N], int t[N][N], int p, int q, int n) {
int i = 0, j = 0;
for (int r= 0; r< n; r++) {
for (int c = 0; c< n; c++) //Copy only those elements which are not in given row r and column c: {
if (r != p && c != q) { t[i][j++] = M[r][c]; //If row is filled increase r index and reset c index
if (j == n - 1) {
j = 0; i++;
}
}
}
}
}
int DET(int M[N][N], int n) //to find determinant {
int D = 0;
if (n == 1)
return M[0][0];
int t[N][N]; //store cofactors
int s = 1; //store sign multiplier //
To Iterate each element of first row
for (int f = 0; f < n; f++) {
//要获取M[0][f]的辅因子,请执行getCfactor(M,t,0,f,n);D+=s*M[0][f]*DET(t,n-1);
s = -s;
}
return D;
}
void ADJ(int M[N][N],int adj[N][N])
//查找伴随矩阵{
if (N == 1) {
adj[0][0] = 1; return;
}
int s = 1,
t[N][N];
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
//辅因子
getCfactor(M, t, i, j, N);
s = ((i+j)%2==0)? 1: -1; //sign of adj[j][i] positive if sum of row and column indexes is even.
adj[j][i] = (s)*(DET(t, N-1)); //Interchange rows and columns to get the transpose of the cofactor matrix
}
}
}
bool INV(int M[N][N], float inv[N][N]) {
int det = DET(M, N);
if (det == 0) {
cout << "can't find its inverse";
return false;
}
int adj[N][N]; ADJ(M, adj);
for (int i=0; i<N; i++) for (int j=0; j<N; j++) inv[i][j] = adj[i][j]/float(det);
return true;
}
template<class T> void print(T A[N][N]) //print the matrix. {
for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << " "; cout << endl; }
}
int main() {
int M[N][N] = {
{1, 2, 3, 4,-2}, {-5, 6, 7, 8, 4}, {9, 10, -11, 12, 1}, {13, -14, -15, 0, 9}, {20 , -26 , 16 , -17 , 25}
};
float inv[N][N];
cout << "Input matrix is :\n"; print(M);
cout << "\nThe Inverse is :\n"; if (INV(M, inv)) print(inv);
return 0;
}输出结果
Input matrix is : 1 2 3 4 -2 -5 6 7 8 4 9 10 -11 12 1 13 -14 -15 0 9 20 -26 16 -17 25 The Inverse is : 0.0811847 -0.0643008 0.0493814 -0.0247026 0.0237006 -0.126819 -0.0161738 0.0745377 -0.0713976 0.0151639 0.0933664 0.0028245 -0.0111876 -0.0220437 0.0154006 0.143624 0.0582573 -0.0282371 0.0579023 -0.0175466 -0.15893 0.0724272 0.0259728 -0.00100988 0.0150219