检查矩阵在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

以上是 检查矩阵在C ++中是否可逆 的全部内容, 来源链接: utcz.com/z/321750.html

回到顶部