我在Java中创建一个类,用于使用二维数组执行矩阵的简单操作,并且我遇到了我的矩阵乘法方法的问题。每当我测试我的.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++;
}
}
即使我测试的是非常小的矩阵,也会出现这种情况,因此我的代码一定存在问题,但我无法弄清楚它是什么。谢谢你的帮助!
答案 0 :(得分:1)
你没有在内部n循环中递增n。如上所述,for循环在循环预定义次数时更合适。