檢查矩陣在C++中是否可逆
我們將在此處瞭解如何檢查矩陣是否可逆。如果 M 是一個矩陣,則逆矩陣 M-1 為-
$$M^-1=\frac{adj(M)}{|M\lvert}$$
因此,如果 M 的行列式非零,則我們可以獲得逆矩陣;否則,我們將無法獲得其逆矩陣。因此,我們需要檢查行列式是否為非零。求行列式是一個遞迴的過程。我們必須找到子矩陣,然後求其行列式,再將該結果用於最終計算。讓我們看看程式碼,以便更好地理解。
示例
#include <iostream>
#define N 4
using namespace std;
void findCoFactor(int mat[N][N], int mat2[N][N], int p, int q, int n) {
int i = 0, j = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if (row != p && col != q) {
mat2[i][j++] = mat[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
}
int getDeterminant(int mat[N][N], int n) {
int determinant = 0;
if (n == 1)
return mat[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++) {
findCoFactor(mat, temp, 0, f, n);
determinant += sign * mat[0][f] * getDeterminant(temp, n - 1);
sign = -sign;
}
return determinant;
}
bool isMatrixInvertible(int mat[N][N], int n) {
if (getDeterminant(mat, N) != 0)
return true;
else
return false;
}
int main() {
int matrix[N][N] = {
{ 1, 0, 2, -1 },
{ 3, 0, 0, 5 },
{ 2, 1, 4, -3 },
{ 1, 0, 5, 0 }
};
if (isMatrixInvertible(matrix, N))
cout << "The matrix is invetible";
else
cout << "The matrix is not invetible";
}輸出
The matrix is invetible
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP