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<<"输入的矩阵为:"<<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 输入的矩阵为: 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<<"输入的矩阵为:"<<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,则行列式被递归计算。有3个嵌套的for循环与循环变量x,i和j一起使用。这些循环用于计算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 ))
}