二维数组(矩阵)的逆矩阵

问题描述 投票:0回答:1

我已经创建了一个函数来计算矩阵的逆,但是当我运行我的程序时,我无法获得正确的结果。

例如,当我插入如下矩阵时:

A1  A2  A3
(2  1   0)
(1  2   1)
(0  1   2)

我得到这个矩阵:

0.1875    -0.125    0.0625
-0.125      0.25    -0.125
0.0625    -0.125    0.1875

虽然正确的矩阵解决方案是这样的:

3/4 -1/2    1/4
-1/2    1   -1/2
1/4 -1/2    3/4

这是我的代码:

void inverse(double A[][MAX], int n) {

    double B[MAX][MAX];
    double det = 1.0;
    int i, j, k;

    // Initializing B to identity matrix
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            B[i][j] = (i == j) ? 1 : 0;

    // Performing row operations to convert A to identity matrix
    for(k = 0; k < n; k++) {
        // Find the pivot element
        int max_row = k;
        for (i = k + 1; i < n; i++) {
            if (abs(A[i][k]) > abs(A[max_row][k])) {
                max_row = i;
            }
        }
        // Swap the current row with the row with the largest pivot element
        if (max_row != k) {
            for (int col = 0; col < n; col++) {
                swap(A[k][col], A[max_row][col]);
                swap(B[k][col], B[max_row][col]);
            }
            det *= -1;
        }
        // Divide the current row by the pivot element to make it equal to 1
        double pivot = A[k][k];
        if (pivot == 0) {
            cout << "Error: Singular matrix." << endl;
            return;
        }
        det *= pivot;
        for(j = 0; j < n; j++) {
            A[k][j] /= pivot;
            B[k][j] /= pivot;
        }
        // Use the current row to eliminate the pivot elements in the other rows
        for(i = 0; i < n; i++) {
            if(i == k) continue;
            double factor = A[i][k];
            for(j = 0; j < n; j++) {
                A[i][j] -= A[k][j] * factor;
                B[i][j] -= B[k][j] * factor;
            }
        }
    }

    // Multiplying by reciprocal of the determinant
    if(det == 0) {
        cout << "Error: Singular matrix." << endl;
        return;
    }
    det = 1/det;

    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            B[i][j] *= det;

    // Copying the inverse matrix to A
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            A[i][j] = B[i][j];
}
c++ matrix-inverse
1个回答
2
投票

注意行列式是4,你的结果是预期结果的1/4

// 乘以行列式的倒数

你不应该乘以行列式的倒数。如果你已经计算了 A 的辅数,在这种情况下是的,将它乘以行列式的倒数将得到逆。但是你已经有了逆:当 A 变成单位矩阵时,B 一定是逆矩阵。

© www.soinside.com 2019 - 2024. All rights reserved.