title: multiplying 2 matrices of different sizes in java
body: <p>I am trying to multiply one matrix by another which are different sizes. The 1st matrix is 4 x 2, and the 2nd matrix is 2 x 2. Currently, the answer produced for this multiplication is by my program is not correct. Please help.</p>
  
  <pre><code>public class MatrixCipher {
  
      public static void main(String[] args) {
          int[][] matrix = new int[4][2];
          int[][] matrix2 = new int[2][2];
          matrix2[0][0] = 1;
                  matrix2[0][1] = 2;
                  matrix2[1][0] = 3;
                  matrix2[1][1] = 4;
  
          int[][] product = new int[4][2];
  
          for (int m = 0; m &lt; 4; m++) {
              for (int n = 0; n &lt; 2; n++) {
                  matrix[m][n] = (int) (6 * Math.random() + 1);
              }
          }
  
          System.out.print("==1==");
          System.out.println("  ");
          for (int m = 0; m &lt; 4; m++) {
              for (int n = 0; n &lt; 2; n++) {
  
                  System.out.print(matrix[m][n] + "  ");
              }
              System.out.println("  ");
          }
          System.out.print("=====");
          System.out.println("");
          System.out.println("  x");
  
          System.out.print("==2==");
          System.out.println("  ");
          for (int m = 0; m &lt; 2; m++) {
              for (int n = 0; n &lt; 2; n++) {
  
                  System.out.print(matrix2[m][n] + "  ");
              }
              System.out.println("  ");
          }
          System.out.print("=====");
          System.out.println("");
          System.out.println("  =");
  
          for (int m = 0; m &lt; 4; m++) {
              for (int n = 0; n &lt; 2; n++) {
                  for (int f = 0; f &lt; 2; f++) {
                      product[m][n] = matrix[m][n] * matrix2[f][n];
              }
            }
          }
  
          System.out.print("=====");
          System.out.println("  ");
          for (int m = 0; m &lt; 4; m++) {
              for (int n = 0; n &lt; 2; n++) {
  
                  System.out.print(product[m][n] + "  ");
              }
              System.out.println("  ");
         }
          System.out.print("=====");
          System.out.println("");
      }
  
  }
  </code></pre>