gpt4 book ai didi

java - 如何修复 Java 中的矩阵乘法

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:06 24 4
gpt4 key购买 nike

我正在用 Java 创建一个类来使用二维数组对矩阵执行简单的操作。我的矩阵乘法方法遇到了问题。

每当我测试我的 multiply 方法时,没有出现错误,但我的计算机 CPU 使用率增加了很多,我的测试程序永远不会完成。

这是我的乘法方法:

/**
* 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 - 如何修复 Java 中的矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com