java 判断因子,用Java确定辅因子矩阵

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."

解决方案

Frankly, I'm a bit of an idiot.

The matrix I'm using for testing is {{8, 3, 5}, {5, 6, 6}, {1, 7, 6}} but the value I'm checking on Wolfram is {{8, 5, 1}, {3, 6, 7}, {5, 6, 6}}...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值