Matrix Multiplication by User-Defined Function in Java

Exercise:

Write a Java Program for matrix multiplication by user-defined function.

Click Here to View the Solution!
public class MatrixMultiplication {
  
     public static void main(String[] args) {
         int r1 = 2, c1 = 3;
         int r2 = 3, c2 = 2;
         int[][] firstMatrix = { {4,1,7}, {4,5 ,4} };
         int[][] secondMatrix = { {1,3}, {-8, 0}, {0, -6} };
    
         // Calculating matrix multiplication
 int[][] product= multiplyMatrices(firstMatrix, secondMatrix,r1,c1, c2);
         // Command to display product matrix
         displayProduct(product);
     }

  // Function Declaration 
  // Multiplication Function
  public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) {
         int[][] product = new int[r1][c2];
         for(int i = 0; i < r1; i++) {
             for (int j = 0; j < c2; j++) {
                 for (int k = 0; k < c1; k++) {
        product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
                 }
             }
         }
        return product;
     }
    //Function Declaration to display product matrix
     public static void displayProduct(int[][] product) {
         System.out.println("Product of two matrices is: ");
         for(int[] row : product) {
             for (int column : row) {
                 System.out.print(column + "    ");
             }
             System.out.println();
         }
     }
 } 
Click Here to View the Output!
Product of two matrices is: 
 -4    -30    
 -36    -12    
Click Here to View the Explanation!
  • The program mentioned above consists of two functions:
  • The first function is multiplyMatrices() which as indicated by its name, performs multiplication operation on the two matrices and gives a resultant matrix of the product.
  • The second function is displayProduct() which is responsible for printing the output of the multiplication operation on the console.
  • The multiplication operation applies to the two matrices in the following manner:

(a11 x b11) + (a12 x b21) + (a13 x b31)    (a11 x b12) + (a12 x b22) + (a13 x b32)  

(a21 x b11) + (a22 x b21) + (a23 x b31)    (a21 x b12) + (a22 x b22) + (a23 x b32)

  • Placing the values in the above matrix as per the example, results in:

(4 x 1) + (1 x -8) + (7x 0) = -4    (4 x 1) + (1 x 0) + (7 x 4) = -30         

(4 x 1) + ( 5 x -8) + (4 x 0) = -36     (4 x 3) + ( 5 x 0) + (4 x -6) = -12