Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

อernéตของเมทริกซ์ (Determinant of Matrix) ใน C++


นิยาม

Determinant คำนวณได้เฉพาะเมทริกซ์จัตุรัส โดยขยายโคแฟกเตอร์ (Cofactor Expansion) ตามแถวแรก

สำหรับเมทริกซ์ 3×3:

| a b c |
| d e f | = a(ei-fh) - b(di-gf) + c(dh-eg)
| g h i |

อัลกอริธึม Recursive

  1. Base case: 1×1 → ค่าตัวเดียว
  2. สร้าง Cofactor Matrix โดยลบแถว 0 และคอลัมน์ j
  3. Det = Σ (-1)^j × mat[0][j] × det(cofactor)

โปรแกรมตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;

using Matrix = vector<vector<int>>;

Matrix getCofactor(const Matrix& mat, int p, int q) {
    int n = mat.size();
    Matrix temp(n-1, vector<int>(n-1));
    int i=0, j=0;
    for (int row=0; row