簡體   English   中英

Java中的矩陣乘法問題

[英]Matrix Multiplication in Java- Issues

我正在用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++;
    }

}

即使我測試非常小的矩陣時也會發生這種情況,所以它一定是我的代碼的問題,但我無法弄清楚它是什么。 謝謝你的幫助!

你沒有在內部n循環中遞增n。 如上所述,for循環在循環預定次數時更合適。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM