如何修复 Java 中的矩阵乘法
How to fix a matrix multiplication in Java
我正在 Java 中创建一个 class 以使用二维数组对矩阵执行简单的运算。我 运行 遇到了矩阵乘法问题。
每当我测试我的 multiply
方法时,都没有出现错误,但是我的计算机 CPU 利用率增加了很多,我的测试程序永远不会完成。
这是我的multiply
方法:
/**
* Multiplies the first matrix by the entered one
* Assumes width of first matrix and height of second are the same
*
* @param toMultiply: Matrix by which to multiply
* @return product: The first matrix multiplied by the entered one
*/
public Matrix multiply(Matrix toMultiply) {
Matrix product = new Matrix(height, toMultiply.width);
int a = 0, b = 0, n = 0;
double value = 0;
while (a < height) {
while (b < toMultiply.width) {
while (n < width) {
value += matrixArray[a][n] * toMultiply.matrixArray[n][b];
}
product.matrixArray[a][b] = value;
value = 0;
n = 0;
b++;
}
b = 0;
a++;
}
return product;
}
这里我构造的矩阵如下:
private double[][] matrixArray;
private int width;
private int height;
/**
* Constructs a matrix with the specified width and height
*
* @param widthOfMatrix
* @param heightOfMatrix
*/
public Matrix(int heightOfMatrix, int widthOfMatrix) {
height = heightOfMatrix;
width = widthOfMatrix;
matrixArray = new double[height][width];
}
/**
* Enters values into the matrix
*
* @param entries: Each value in a matrix separated by a comma
*/
public void enter(double... entries) {
int a = 0, b = 0;
while (a < height) {
while (b < width) {
matrixArray[a][b] = entries[b + a * width];
b++;
}
b = 0;
a++;
}
}
即使我测试非常小的矩阵也会出现这种情况,所以这一定是我的代码有问题,但我无法弄清楚它是什么。
您没有在内部 n
循环中递增 n
。上面说了,for循环在循环预定义的次数时比较合适。
我正在 Java 中创建一个 class 以使用二维数组对矩阵执行简单的运算。我 运行 遇到了矩阵乘法问题。
每当我测试我的 multiply
方法时,都没有出现错误,但是我的计算机 CPU 利用率增加了很多,我的测试程序永远不会完成。
这是我的multiply
方法:
/**
* Multiplies the first matrix by the entered one
* Assumes width of first matrix and height of second are the same
*
* @param toMultiply: Matrix by which to multiply
* @return product: The first matrix multiplied by the entered one
*/
public Matrix multiply(Matrix toMultiply) {
Matrix product = new Matrix(height, toMultiply.width);
int a = 0, b = 0, n = 0;
double value = 0;
while (a < height) {
while (b < toMultiply.width) {
while (n < width) {
value += matrixArray[a][n] * toMultiply.matrixArray[n][b];
}
product.matrixArray[a][b] = value;
value = 0;
n = 0;
b++;
}
b = 0;
a++;
}
return product;
}
这里我构造的矩阵如下:
private double[][] matrixArray;
private int width;
private int height;
/**
* Constructs a matrix with the specified width and height
*
* @param widthOfMatrix
* @param heightOfMatrix
*/
public Matrix(int heightOfMatrix, int widthOfMatrix) {
height = heightOfMatrix;
width = widthOfMatrix;
matrixArray = new double[height][width];
}
/**
* Enters values into the matrix
*
* @param entries: Each value in a matrix separated by a comma
*/
public void enter(double... entries) {
int a = 0, b = 0;
while (a < height) {
while (b < width) {
matrixArray[a][b] = entries[b + a * width];
b++;
}
b = 0;
a++;
}
}
即使我测试非常小的矩阵也会出现这种情况,所以这一定是我的代码有问题,但我无法弄清楚它是什么。
您没有在内部 n
循环中递增 n
。上面说了,for循环在循环预定义的次数时比较合适。