【问题标题】:Determining Cofactor Matrix in Java在 Java 中确定辅因子矩阵
【发布时间】:2014-01-16 05:12:40
【问题描述】:

我正在尝试确定一个辅因子矩阵。我的代码正确生成了所有辅因子;但是,在某些情况下,生成的矩阵会旋转 90 度(好吧,列/行已切换)。

例如,矩阵:{{8, 5, 1}, {3, 6, 7}, {5, 6, 6}} 产生了正确的结果。

输出 >

a
8 3 5 
5 6 6 
1 7 6 

a
-6 17 -12 
-24 43 -23 
29 -53 33 

但是,矩阵:{{1, 0, 5}, {9, 3, 0}, {0, 9, 3}} 切换行和列。

输出>

b
1 0 5 
9 3 0 
0 9 3 

b
9 45 -15 
-27 3 45 
81 -9 3 

正确的结果是:

9 -27 81
45 3 -9
-15 45 3

矩阵是这样存储的:

Matrix:
    int matrix[][]
    int rows
    int cols

rows 和 cols 确实是必要的,但每次我试图确定我正在使用多少个值时,它都比使用 matrix.length 更好。

这里是生成这些矩阵的代码:

public Matrix cofactor() {
    Matrix result = new Matrix(this.rows, this.cols);
    for (int i = 0; i < result.rows; i++) {
        for (int j = 0; j < result.cols; j++) {
            result.matrix[j][i] = (int)(Math.pow(-1, i + j) * removeRowCol(i, j).determinant());
        }
    }

    return result;
}

public Matrix removeRowCol(int row, int col) {
    Matrix result = new Matrix(this.rows - 1, this.cols - 1);

    int k = 0, l = 0;
    for (int i = 0; i < this.rows; i++) {
        if (i == row) continue;
        for (int j = 0; j < this.cols; j++) {
            if (j == col) continue;
            result.matrix[l][k] = this.matrix[i][j];

            k = (k + 1) % (this.rows - 1);
            if (k == 0) l++;
        }
    }

    return result;
}

行列式部分现在有点小问题,但它适用于 3x3 和 2x2 矩阵。

public int determinant() {
    if (this.rows == 2) return this.matrix[0][0] * this.matrix[1][1] - this.matrix[0][1] * this.matrix[1][0];

    int determinant1 = 0, determinant2 = 0;
    for (int i = 0; i < this.rows; i++) {
        int temp = 1, temp2 = 1;
        for (int j = 0; j < this.cols; j++) {
            temp *= this.matrix[(i + j) % this.cols][j];
            temp2 *= this.matrix[(i + j) % this.cols][this.rows - 1 - j];
        }

        determinant1 += temp; 
        determinant2 += temp2;
    }

    return determinant1 - determinant2;
}

无论如何,我一直在试图弄清楚为什么只有某些矩阵被“旋转”。

【问题讨论】:

    标签: java matrix linear-algebra


    【解决方案1】:

    坦率地说,我有点白痴。

    我用于测试的矩阵是 {{8, 3, 5}, {5, 6, 6}, {1, 7, 6}},但我在 Wolfram 上检查的值是 {{8, 5, 1}, {3, 6, 7}, {5, 6, 6}}...

    【讨论】:

    • 无论如何,谢谢你让我记住了辅因子矩阵是什么=)
    猜你喜欢
    • 2019-11-18
    • 2011-09-25
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多