I'm trying to determine a cofactor matrix. My code is correctly generating all the cofactors; however, in some cases, the resulting matrix is rotated by 90 degrees (well, the cols/rows are switched).
For example, the matrix: {{8, 5, 1}, {3, 6, 7}, {5, 6, 6}} produced the correct result.
output >
a
8 3 5
5 6 6
1 7 6
a
-6 17 -12
-24 43 -23
29 -53 33
however, the matrix: {{1, 0, 5}, {9, 3, 0}, {0, 9, 3}} switches rows and columns.
output >
b
1 0 5
9 3 0
0 9 3
b
9 45 -15
-27 3 45
81 -9 3
the correct result is:
9 -27 81
45 3 -9
-15 45 3
The matrices are stored thusly:
Matrix:
int matrix[][]
int rows
int cols
rows and cols are really necessary, but it's nicer than using matrix.length every time I'm trying to determine how many values I'm working with.
here is the code that generates these matrices:
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;
}
the determinant part is a bit of a hack, now, but it works for 3x3 and 2x2 matrices.
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;
}
Anyways, I'm stuck trying to figure out why only certain matrices are "rotated."