Search code examples
javaarraysmultidimensional-arraymatrix-multiplication

Using Multi-Dimensional Arrays for Matrix Multiplication Java


I'm trying to write a code that multiplies two given matrices together and displays the results. Here is the code I have down so far:

public static void main(String[] args) {
    double firstMatrix[][] = {{1, 2}, {3, 4}, {5, 6}};
    double secondMatrix[][] = {{1, 2, 3}, {4, 5, 6}};

    double[][] thirdMatrix = multiplyMatrix((firstMatrix), (secondMatrix));

    System.out.println("The product of the matrices is ");
    for (int i = 0; i < thirdMatrix.length; i++) {
        for (int j = 0; j < thirdMatrix[0].length; j++) {
            System.out.print(firstMatrix[i][j] + " ");
            if (i == 1 && j == 2) {
                System.out.print("  *  ");
            } else {
                System.out.print("    ");
            }
        }
        for (int j = 0; j < thirdMatrix[0].length; j++) {
            System.out.print(secondMatrix[i][j] + " ");
            if (i == 1 && j == 2) {
                System.out.print(" = ");
            } else {
                System.out.print("  ");
            }
        }
        for (int j = 0; j < thirdMatrix[0].length; j++) {
            System.out.printf("%.1f", thirdMatrix[i][j]);
        }
        System.out.println();
    }
}
public static double[][] multiplyMatrix(double[][] a, double[][] b) {
    double c[][] = new double[3][3];
    for (int i = 0; i < c.length; i++) {
        for (int j = 0; j < b.length; j++) {
            for (int k = 0; k < a.length; k++) {
                c[i][j] += ((a[i][k]) * (b[k][j]));
            }
        }
    }
    return c;
}

But when I try to execute the program I receive an Array Index out of Bounds Error which shouldn't be the case since my for loops are making sure not to step out of bounds from the array. I don't understand where to change my code because it looks fine until I try to execute. Any help is really appreciated.


Solution

  • If 1st matrix's dimensions is mxn and the 2nd's nxp then the product's dimensions mxp. Right?
    So this 2nd level of the triple loop should iterate through the 2nd dimension of the product array:

    for (int j = 0; j < b.length; j++)
    

    should be:

    for (int j = 0; j < b[0].length; j++)
    

    b[0].length is the number of columns of the matrix b.
    Also the 3d level of the triple loop should be:

    for (int k = 0; k < b.length; k++)
    

    b.length is the number of rows of the matrix b which is equal to the number of columns of the matrix a.
    Edit
    In a generalized version you could change this:

    double c[][] = new double[3][3];
    

    to

    double c[][] = new double[a.length][b[0].length];