-1

I'm writing a program for class where we hard code matrices in a driver class and put the matrix operations in a matrix class. I'm running into an issue where I get the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

I'm pretty sure that it's the second for loop but I can't think of what range to do to refer to the columns of the hard coded matrix in the driver class.

row and col are both instantiated in the Matrix class and I fixed the j++ but it still gives the same error even when I'm doing a 1x2 multiplied by a 2x3, for example

public Matrix mult(Matrix m) {
    // TODO: Multiply the two matrices, store the value
    // in a new matrix and return that matrix
    Matrix m5 = new Matrix(new int[row][col]);
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < m.myMatrix[0].length; j++) {
            for (int k = 0; k < col; k++) {
                m5.myMatrix[i][j] += myMatrix[i][k] * m.myMatrix[k][j];
            }
        }
    }
    return m5;
}
Community
  • 1
  • 1
PSqc
  • 9
  • 2
  • Second loop's increment part must be `j++` and not `i++` – Thiyagu Feb 25 '18 at 04:09
  • Your error is because you initialized `m5` with size `row x col`, and you assign to `m5.myMatrix[i][j]`, so `i` should loop `row` times, and `j` should loop `col` times, but it's `k` not `j` that loops that many times. You seem to have mixed up the loop variables. – Andreas Feb 25 '18 at 05:18

1 Answers1

1

I do not see that row and col are being instantiated anywhere, so I'm guessing that you are using member variables of the Matrix class. Your resulting matrix shouldn't be the same size as the original matrix unless they are both square matricies. For example, if you multiply a 4X2 matrix by a 2X3 matrix, it should result in a 4X3 matrix. Wikipedia provides an example of this.