Skip to content
Advertisement

How to fix a matrix multiplication in Java

I’m creating a class in Java to perform simple operations with matrices using two-dimensional arrays. I’m running into a problem with my method for matrix multiplication.

Whenever I test my multiply method, no error appears, but my computer CPU utilization increases quite a bit and my tester program never finishes.

This is my multiply method:

/**
 * 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;
}

Where I construct a matrix as follows:

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++;
    }
}

This occurs even when I test very small matrices, so it must be a problem with my code, but I can’t figure out what it is.

Advertisement

Answer

You’re not incrementing n in your inner n loop. As is mentioned above, for loops are more appropriate when looping a predefined number of times.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement