2014-01-16 20 views
2

我在試圖確定一個輔助矩陣。我的代碼正確生成所有的輔助因素;然而,在某些情況下,產生的矩陣旋轉了90度(好,列/行被切換)。在Java中確定Cofactor矩陣

例如,矩陣:{{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; 
} 

行列式的部分是一個黑客攻擊的一位,現在,但它工作在3×3和2×2矩陣。

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; 
} 

無論如何,我試圖弄清楚爲什麼只有某些矩陣被「旋轉」。

回答

1

坦率地說,我有點白癡。

我使用的測試矩陣是{{8, 3, 5}, {5, 6, 6}, {1, 7, 6}}但我檢查的鎢值{{8, 5, 1}, {3, 6, 7}, {5, 6, 6}} ...

+1

無論如何,感謝讓我記住的輔因子矩陣是什麼=) – Scadge