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

โปรแกรม C++ ตรวจสอบว่าเมทริกซ์ Invertible ได้หรือไม่


Determinant ใช้ตรวจสอบว่าเมทริกซ์ Invertible (คูณผกกได้) หรือไม่ เมทริกซ์ Invertible ได้ก็ต่อเมื่อ Determinant ≠ 0 หาก Determinant = 0 เมทริกซ์ไม่ Invertible

ตัวอย่าง:

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

Determinant = 3 → เมทริกซ์ Invertible ได้

ตัวอย่างโค้ด

#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, d, 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;
    }
    d = determinant(matrix, n);
    cout << "Determinant of the matrix is " << d << endl;
    if (d == 0)
        cout << "This matrix is not invertible as the determinant is zero";
    else
        cout << "This matrix is invertible as the determinant is not zero";
    return 0;
}

ผลลัพธ์

Enter the size of the matrix: 3
Enter the elements of the matrix: 1 2 3 2 1 2 1 1 4
The entered matrix is:
1 2 3
2 1 2
1 1 4
Determinant of the matrix is -7
This matrix is invertible as the determinant is not zero

อธิบายโค้ดสำคัญ

คำนวณ Determinant แบบ Recursive เหมือนบทความก่อนหน้า แล้วเช็คค่า d:

d = determinant(matrix, n);
cout<<"Determinant of the matrix is "<< d <<endl;
if( d == 0 )
    cout<<"This matrix is not invertible as the determinant is zero";
else
    cout<<"This matrix is invertible as the determinant is not zero";