Limbo
Limbo

Reputation: 101

Matrix Multiplication Error { Happen to know the error but having difficulties fixing it}

Fortunately, I think I know why the code isn't working but I am just having difficulties fixing it. The error that I am getting is java.lang.ArrayIndexOutOfBoundsException: 2. What I believe is incorrect here is on the last line of code when the for loops increment up to 2, 'j' in Matrix2 [k] [j] denotes columns and since the columns can't be more than 1 in Matrix2, I get that error. The result that I should be getting by multiplying both the matrices :

 -3 43
  18 -60
  1 -20                           

int[][] Matrix1 = {{1,2,-2,0},
                   {-3,4,7,2},
                   {6,0,3,1}};

int[][] Matrix2 = {{1,3},
                    {0,9},
                    {1,-11},
                    {4,-5}}; 

 int [][] MultipliedMatrix = new int [3][2];    


  for (int i=0; i<Matrix1.length; i++)
      for (int j=0; j<Matrix2.length; j++)
          for (int k=0; k<Matrix2.length; k++)

             MultipliedMatrix[i][j] += Matrix1[i][k] * Matrix2[k][j] ; 

Upvotes: 0

Views: 110

Answers (1)

ben_joseph
ben_joseph

Reputation: 1681

matrix.length returns the number of rows while matrix[0].length returns the number of columns.

Upvotes: 1

Related Questions