C++中矩陣的行列式?
矩陣的行列式只能針對方陣計算,方法是將第一行餘子式乘以相應餘子式的行列式,並用交替的正負號將它們加起來,得到最終結果。
$$A = \begin{bmatrix}a & b & c \\ d & e & f \\ g & h & i \end{bmatrix} |A| = a(ei-fh)-b(di-gf)+c(dh-eg)$$
首先,我們有 `determinantOfMatrix(int mat[N][N], int dimension)` 函式,它接受矩陣和矩陣的維數作為引數。如果矩陣只有一維,則返回 `[0][0]` 的矩陣值。此條件也用作基本條件,因為我們透過遞迴呼叫在每次遞迴呼叫中減少維數來遞迴迭代矩陣。
int determinantOfMatrix(int mat[N][N], int dimension){
int Det = 0;
if (dimension == 1)
return mat[0][0];然後,我們宣告 `cofactorMat[N][N]`,它將傳遞給 `cofactor(int mat[N][N], int temp[N][N], int p, int q, int n)` 函式,直到 `firstRow` 小於維數。矩陣的行列式儲存在 `Det` 變數中,符號在每次 for 迴圈迭代時交替。然後將此 `det` 返回到主函式,在主函式中列印它。
int cofactorMat[N][N];
int sign = 1;
for (int firstRow = 0; firstRow < dimension; firstRow++){
cofactor(mat, cofactorMat, 0, firstRow, dimension);
Det += sign * mat[0][firstRow] * determinantOfMatrix(cofactorMat, dimension - 1);
sign = -sign;
}
return Det;
}`cofactor(int mat[N][N], int temp[N][N], int p,int q, int n)` 函式以矩陣、餘子式矩陣、0、`firstRow` 值和矩陣的維數作為引數值。然後,巢狀的 for 迴圈幫助我們遍歷矩陣,當 p & q 值分別不等於行和列值時,這些值將儲存在 temp 矩陣中。
void cofactor(int mat[N][N], int temp[N][N], int p,int q, int n){
int i = 0, j = 0;
for (int row = 0; row < n; row++){
for (int column = 0; column < n; column++){
if (row != p && column != q){
temp[i][j++] = mat[row][column];一旦行填滿,我們就增加行索引並重置列索引。
if (j == n - 1){
j = 0;
i++;
}最後,我們有 `display(int mat[N][N], int row, int col)` 函式,它接受矩陣以及行數和列數,並以二維陣列的形式迭代矩陣,並在每一行和每一列列印這些值。
void display(int mat[N][N], int row, int col){
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}示例
讓我們看看以下實現來查詢矩陣的行列式。
#include <iostream>
using namespace std;
const int N = 3;
void cofactor(int mat[N][N], int temp[N][N], int p,int q, int n){
int i = 0, j = 0;
for (int row = 0; row < n; row++){
for (int column = 0; column < n; column++){
if (row != p && column != q){
temp[i][j++] = mat[row][column];
if (j == n - 1){
j = 0;
i++;
}
}
}
}
}
int determinantOfMatrix(int mat[N][N], int dimension){
int Det = 0;
if (dimension == 1)
return mat[0][0];
int cofactorMat[N][N];
int sign = 1;
for (int firstRow = 0; firstRow < dimension; firstRow++){
cofactor(mat, cofactorMat, 0, firstRow, dimension);
Det += sign * mat[0][firstRow] * determinantOfMatrix(cofactorMat, dimension - 1);
sign = -sign;
}
return Det;
}
void display(int mat[N][N], int row, int col){
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
int main(){
int mat[3][3] = {
{ 1, 0, 2},
{ 3, 0, 0},
{ 2, 1, 4}};
cout<<"The matrix is "<<endl;
display(mat,3,3);
cout<<"Determinant of the matrix is "<<determinantOfMatrix(mat, N);
return 0;
}輸出
以上程式碼將產生以下輸出:
The matrix is 1 0 2 3 0 0 2 1 4 Determinant of the matrix is 6
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP