C++程序:检查矩阵是否可逆
矩阵的行列式可以用来判断它是否可逆。如果行列式不为零,则矩阵可逆。因此,如果行列式为零,则矩阵不可逆。例如:
The given matrix is: 4 2 1 2 1 1 9 3 2 The determinant of the above matrix is: 3 So the matrix is invertible.
下面是一个检查矩阵是否可逆的程序。
示例
#include<iostream> #include<math.h> using namespace std; int determinant( int matrix[10][10], int n) { int det = 0; int submatrix[10][10]; if (n == 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1])); else { for (int x = 0; x < n; x++) { int subi = 0; for (int i = 1; i < n; i++) { int subj = 0; for (int j = 0; j < n; j++) { if (j == x) continue; submatrix[subi][subj] = matrix[i][j]; subj++; } subi++; } det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 )); } } return det; } int main() { int n, d, i, j; int matrix[10][10]; cout << "Enter the size of the matrix:\n"; cin >> n; cout << "Enter the elements of the matrix:\n"; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> matrix[i][j]; cout<<"The entered matrix is:"<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << matrix[i][j] <<" "; cout<<endl; } d = determinant(matrix, n); cout<<"Determinant of the matrix is "<< d <<endl; if( d == 0 ) cout<<"This matrix is not invertible as the determinant is zero"; else cout<<"This matrix is invertible as the determinant is not zero"; return 0; }
输出
Enter the size of the matrix: 3 Enter the elements of the matrix: 1 2 3 2 1 2 1 1 4 The entered matrix is: 1 2 3 2 1 2 1 1 4 Determinant of the matrix is -7 This matrix is invertible as the determinant is not zero
在上面的程序中,矩阵的大小和元素在`main()`函数中给出。然后调用`determinant()`函数。它返回矩阵的行列式,并将其存储在`d`中。如果行列式为0,则矩阵不可逆;如果行列式不为0,则矩阵可逆。以下代码片段演示了这一点。
cout << "Enter the size of the matrix:\n"; cin >> n; cout << "Enter the elements of the matrix:\n"; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> matrix[i][j]; cout<<"The entered matrix is:"<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << matrix[i][j] <<" "; cout<<endl; } d = determinant(matrix, n); cout<<"Determinant of the matrix is "<< d <<endl; if( d == 0 ) cout<<"This matrix is not invertible as the determinant is zero"; else cout<<"This matrix is invertible as the determinant is not zero";
在`determinant()`函数中,如果矩阵的大小为2,则直接计算行列式并返回其值。如下所示:
if (n == 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
如果矩阵的大小不是2,则递归计算行列式。使用循环变量`x`、`i`和`j`使用了3个嵌套循环。这些循环用于计算行列式,并递归调用`determinant()`函数来计算内部行列式,然后将其与外部值相乘。以下代码片段演示了这一点。
for (int x = 0; x < n; x++) { int subi = 0; for (int i = 1; i < n; i++) { int subj = 0; for (int j = 0; j < n; j++) { if (j == x) continue; submatrix[subi][subj] = matrix[i][j]; subj++; } subi++; } det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 )) }
广告