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 ))
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP