我的代码有问题, 该算法是正确的,但我不明白为什么方法matrixInverse改变矩阵的值.MatrixInverse只返回身份。
我该如何解决?
public class Main {
public static void main(String[] args){
double[][] matrix = new double[][]{{ 56, 0, 0, 34, 0, 0},
{ 0, 1, 0, 0, 0, 0},
{ 0, 0, 1, 0, 0, 0},
{ 1, 0, 0, 1, 0, 0},
{ 0, 0, 0, 0, 1, 0},
{ 0, 0, 0, 0, 0, 1},
};
double[][] inverse = MathUtilities.matrixInverse(matrix);
}
}
方法matrixInverse:
public static double[][] matrixInverse(double[][] mat) throws ArithmeticException {
if (mat.length != mat[0].length) {
System.err.println("Matrix is not square");
ArithmeticException e = new ArithmeticException();
throw e;
}
double[][] matrix = mat;
double[][] identity = new double [matrix.length][matrix.length];
//----------------------------------------------------------------------
for(int i = 0;i < matrix.length;++i)
{
for(int j = 0;j < matrix.length; ++j)
{
if(i == j)
identity[i][j] = 1;
else
identity[i][j] = 0;
}
}
//----------------------------------------------------------------------
for(int i = 0; i < matrix.length; ++i)
{
for(int j = i + 1 ; j < matrix.length; ++j)
{
double constant = matrix[j][i]/matrix[i][i];
for(int k = 0; k < matrix.length; ++k)
{
matrix[j][k] = matrix[j][k] - (constant * matrix[i][k]);
identity[j][k] = identity[j][k] - (constant * identity[i][k]);
}
}
}
//----------------------------------------------------------------------
for(int i = matrix.length - 1;i >= 0; --i)
{
for(int j = i - 1; j >= 0; --j)
{
double constant1 = matrix[j][i]/matrix[i][i];
for(int k = matrix.length - 1 ; k >= 0; k--)
{
matrix[j][k] = matrix[j][k] - constant1 * matrix[i][k];
identity[j][k] = identity[j][k] - constant1 * identity[i][k];
}
}
}
//----------------------------------------------------------------------
for(int i = 0 ; i < matrix.length; ++i)
{
for(int j = 0;j < matrix.length; ++j)
{
identity[i][j]=identity[i][j]/matrix[i][i];
}
}
System.out.println("The inverse matrix is");
return identity;
}
答案 0 :(得分:3)
double[][] matrix = mat;
在这行代码中,您要分配引用,而不是复制对象。因此,如果您更改matrix
或mat
,则实际上是在更改同一个对象。
答案 1 :(得分:0)
同样值得看shallow vs deep copying。深层复制将使您的原始矩阵不被修改。