C程序 查找矩阵定数
什么是矩阵的决定数?
矩阵的行列式是一个特殊的数字,只对方形矩阵(行数和列数相同的矩阵)定义。在微积分和其他与代数有关的矩阵中,行列式在很多地方都有使用,它实际上是用一个实数来表示矩阵,可用于求解线性方程组和寻找矩阵的逆数。
如何计算?
对于第一行或第一列的每个元素,得到这些元素的协整数,然后将该元素与相应协整数的行列式相乘,最后用交替符号相加。作为一个基本情况,1*1矩阵的行列式的值是单值本身。
一个元素的系数是一个矩阵,我们可以通过从该矩阵中去除该元素的行和列来得到。
2×2矩阵的决定数:
3×3矩阵的决定数:
// C program to find Determinant
// of a matrix
#include <stdio.h>
// Dimension of input square matrix
#define N 4
// Function to get cofactor of mat[p][q]
// in temp[][]. n is current dimension
// of mat[][]
void getCofactor(int mat[N][N], int temp[N][N],
int p, int q, int n)
{
int i = 0, j = 0;
// Looping for each element of the matrix
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
// Copying into temporary matrix
// only those element which are
// not in given row and column
if (row != p && col != q)
{
temp[i][j++] = mat[row][col];
// Row is filled, so increase row
// index and reset col index
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
/* Recursive function for finding the
determinant of matrix. n is current
dimension of mat[][]. */
int determinantOfMatrix(int mat[N][N], int n)
{
// Initialize result
int D = 0;
// Base case : if matrix contains
// single element
if (n == 1)
return mat[0][0];
// To store cofactors
int temp[N][N];
// To store sign multiplier
int sign = 1;
// Iterate for each element of
// first row
for (int f = 0; f < n; f++)
{
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n);
D += sign * mat[0][f]
* determinantOfMatrix(temp, n - 1);
// Terms are to be added with alternate sign
sign = -sign;
}
return D;
}
// Function for displaying the matrix
void display(int mat[N][N],
int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
printf(" %d", mat[i][j]);
printf("n");
}
}
// Driver code
int main()
{
int mat[N][N] = {{1, 0, 2, -1},
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}};
// Function call
printf("Determinant of the matrix is : %d",
determinantOfMatrix(mat, N));
return 0;
}
输出
Determinant of the matrix is : 30