Search code examples
javamatrix-multiplication

My matrix multiplication function is returning blank or incorrect outputs


The function I've written to multiply matrices is not properly out putting or is giving me a blank one. It managed to give me one correct output though I can't get find that array anymore.

When I inputted
int[][] test = new int[][]{ {2, 4}, {5, 3}, {3, 5} }; int[][] test2 = new int[][]{ {3, 4, 2}, {5, 1, 2} };
It's return an array of zeros


    int[][] toRet = new int[arr1.length][arr2[0].length];

    for(int i = 0; i < arr1.length; i++){
      for(int j = 0; j < arr2[0].length; j++){
        for(int k = 02; k < arr1[0].length; k++){
          toRet[i][j] += arr1[i][k] * arr2[k][j];
        }
      }
    }

    return toRet;
  }```  

It worked for a minute and I didn't change anything but my test.

Solution

  • Your 3rd loop is wrong. You initialized k with 2, it should be k=0. Now taking your example. Your matrix is

    int[][] test = new int[][]{
          {2, 4},
          {5, 3},
          {3, 5}
        };
    

    arr1[0].length will return 2 as there are 2 elements only and k < arr1[0].length will return false. So your 3rd loop will exit without any summation and multiplications. That is why you are getting all elements 0. Change your 3rd loop to k=0, which looks like this:

    for(int i = 0; i < arr1.length; i++){
          for(int j = 0; j < arr2[0].length; j++){
            for(int k = 0; k < arr1[0].length; k++){
              toRet[i][j] += arr1[i][k] * arr2[k][j];
            }
          }
        }