Multiplication of two Matrices using Java


Matrix multiplication leads to a new matrix by multiplying 2 matrices. But this is only possible if the columns of the first matrix are equal to the rows of the second matrix. An example of matrix multiplication with square matrices is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String args[]) {
      int n = 3;
      int[][] a = { {5, 2, 3}, {2, 6, 3}, {6, 9, 1} };
      int[][] b = { {2, 7, 5}, {1, 4, 3}, {1, 2, 1} };
      int[][] c = new int[n][n];
      System.out.println("Matrix A:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(a[i][j] + " ");
         }
         System.out.println();
      }
      System.out.println("Matrix B:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(b[i][j] + " ");
         }
         System.out.println();
      }
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++){
            for (int k = 0; k < n; k++) {
               c[i][j] = c[i][j] + a[i][k] * b[k][j];
            }
         }
      }
      System.out.println("The product of two matrices is:");
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            System.out.print(c[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Output

Matrix A:
5 2 3
2 6 3
6 9 1
Matrix B:
2 7 5
1 4 3
1 2 1
The product of two matrices is:
15 49 34
13 44 31
22 80 58

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements