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

โปรแกรม C++ คำนวณ Determinant ของเมทริกซ์


Determinant (ดетерมิแนนท์) ของเมทริกซ์สี่เหลี่ยมจัตุรัส คำนวณจากค่าองค์ประกอบ สัญลักษณ์ det(A) เรียกว่า Scaling Factor ของ Linear Transformation ที่เมทริกซ์อธิบายในเรขาคณิต

ตัวอย่าง เมทริกซ์ 2×2:

เมทริกซ์:
3 1
2 7

Determinant = 7×3 - 2×1 = 21 - 2 = 19

ตัวอย่างโค้ด (รองรับเมทริกซ์ n×n)

#include <iostream>
#include <math.h>
using namespace std;

int determinant(int matrix[10][10], int n) {
    int det = 0;
    int submatrix[10][10];
    if (n == 2)
        return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
    else {
        for (int x = 0; x < n; x++) {
            int subi = 0;
            for (int i = 1; i < n; i++) {
                int subj = 0;
                for (int j = 0; j < n; j++) {
                    if (j == x) continue;
                    submatrix[subi][subj] = matrix[i][j];
                    subj++;
                }
                subi++;
            }
            det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n - 1));
        }
    }
    return det;
}

int main() {
    int n, i, j;
    int matrix[10][10];
    cout << "Enter the size of the matrix:\n";
    cin >> n;
    cout << "Enter the elements of the matrix:\n";
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            cin >> matrix[i][j];
    cout << "The entered matrix is:" << endl;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            cout << matrix[i][j] << " ";
        cout << endl;
    }
    cout << "Determinant of the matrix is " << determinant(matrix, n);
    return 0;
}

ผลลัพธ์

Enter the size of the matrix: 3
Enter the elements of the matrix: 7 1 3 2 4 1 1 5 1
The entered matrix is:
7 1 3
2 4 1
1 5 1
Determinant of the matrix is 10

อธิบายการทำงาน

ใน main() รับขนาดและค่าองค์ประกอบเมทริกซ์ แล้วเรียก determinant() แสดงผล:

cout << "Enter the size of the matrix:\n";
cin >> n;
cout << "Enter the elements of the matrix:\n";
for (i = 0; i < n; i++)
    for (j = 0; j < n; j++)
        cin >> matrix[i][j];
cout<<"The entered matrix is:"<<endl;
for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++)
        cout << matrix[i][j] << " ";
    cout<<endl;
}
cout<<"Determinant of the matrix is "<< determinant(matrix, n);

ใน determinant() ถ้า n=2 คำนวณตรงๆ สูตร ad-bc:

if (n == 2)
    return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));

ถ้า n>2 คำนวณแบบ Recursive ด้วย 3 นested loops (x, i, j) สร้าง submatrix แล้วเรียก determinant() ซ้ำ:

for (int x = 0; x < n; x++) {
    int subi = 0;
    for (int i = 1; i < n; i++) {
        int subj = 0;
        for (int j = 0; j < n; j++) {
            if (j == x) continue;
            submatrix[subi][subj] = matrix[i][j];
            subj++;
        }
        subi++;
    }
    det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n - 1));
}