Problem: Write a Java program to multiply two matrices and output the resultant matrix.

Example:

m1 = {{1, 2, 3},  
      {1, 1, 1}}

m2 = {{1, 2},
      {1, 3},
      {1, 1}}   

m1*m2 =  {{6, 11},
          {3, 6}}
Matrix multiplication in C

Two matrices A and B can only be multiplied, if the number of columns in A is equal to the number of rows in B and the order of the resultant matrix would be (rows of A x columns of B).

Knowing all this, we can multiply two matrix in Java as follows:

  1. Input matrix1 and matrix2
  2. Declare empty resultant matrix of order (r1, c2)
  3. Loop from 0 to result.length as i:
    1. Nest another loop from 0 to result[0].length as j:
      1. Nest another loop from 0 to matrix1[0].length as k:
        1. Sum (matrix1[I][K] * matrix2[K][J])
      2. Store the sum into the resultant matrix as result[i][j]=sum
    2. End loop.
  4. End loop.
  5. Output the resultant matrix.

Here is the Java program that implements the above logic to multiply two matrices:

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
 
    //matrix-I
    int matrix1[][] = {{1, 2, 3},
                      {1, 1, 1}};
         
    //matrix-II          
    int matrix2[][] = {{1, 2},
                       {1, 3},
                       {1, 1}}; 
 
    //declare resultant matrix of order (1st.row x 2nd.col)
    int result[][] = new int[2][2];
 
    //matrix multiplication algorithm
    for(int i=0; i<result.length; i++){
      for(int j=0; j<result[0].length; j++){
        int sum=0;
        for(int k=0; k<matrix1[0].length; k++){
            sum += matrix1[i][k]*matrix2[k][j];
        }
        result[i][j] = sum;
      }
    }
 
    //display the resultant matrix
    System.out.println("Resultant Matrix");
    for(int i=0; i<result.length; i++){
        for(int j=0; j<result[0].length; j++){
            System.out.print(result[i][j]+ " ");
        }
        System.out.println();
    }
    
  }
}

Output:

Resultant Matrix
6 11
3 6

Leave a Reply