-1

This method works for multiplication of 2x2 and 2x2 matrices only, but it's not working for 3x2 and 2x3. It results in

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

What am I doing wrong?

public class MultiplyMatrix {
    public static int[][] multiply(int[][] a, int[][] b) {

        int r1 = a[0].length, c1 = a.length; //2 3
        int r2 = b[0].length, c2 = b.length; //3 2

        int[][] multiply = new int[r1][c2];

        for (int i = 0; i < r1; i++) {
            for (int j = 0; j < c2; j++) {
                for (int k = 0; k < c1; k++) {
                    multiply[i][j] += a[i][k] * b[k][j];
                }
            }
        }
        return multiply;
    }

    public static void main(String[] args) {

        System.out.println("Test your code here!\n");

        // Get a result of your code

        int[][] a = { {1, 2, 3}, {4, 5, 6} };
        int[][] b = { {7, 8}, {9, 10}, {11, 12} };


        int[][] result = multiply(a, b);
        System.out.println(Arrays.deepToString(result).replace("],", "]\n"));
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

I think, you should edit the code like this

...
        int r1 = a.length, c1 = a[0].length; //2 3
        int r2 = b.length, c2 = b[0].length; //3 2
...
fixcer
  • 129
  • 1
  • 5