java - 在 Java 中确定辅因子矩阵

标签 java matrix linear-algebra

我正在尝试确定辅助因子矩阵。我的代码正确生成了所有辅因子;然而,在某些情况下,生成的矩阵会旋转 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

行和列确实是必要的,但它比每次我尝试确定正在使用的值的数量时使用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;
}

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

最佳答案

说实话,我有点白痴。

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

关于java - 在 Java 中确定辅因子矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21153823/

相关文章:

go - Go 中的并行 saxpy 实现不能很好地跨内核扩展

java - 这会通过标签名称 "c"获取元素吗?在我的程序中它不起作用?

python - 将方阵缩放/调整为更大的尺寸,同时保留网格结构/图案 (Python)

Python:按列值分隔矩阵

python - super 简单示例的不正确的 Python Numpy 特征向量值

language-agnostic - 多元对分法

Java JACOB 检索给定 Win32_* 类对象的所有属性

java - BufferedImage调整算法

c# - WCF 与 Java Web 服务通信

matrix - 在 Racket 中设置多维向量的各个元素