Saturday 14 September 2019

Java Program to Perform Matrix Multiplication

          In the current post, I have written a java program to perform a simple matrix multiplication. For matrix multiplication the column of the first matrix should be equal to the row of the second matrix, then only we can perform matrix multiplication.

         In matrix multiplication, one row element of first matrix is multiplied by all columns of second matrix.
Matrix multiplication
Matrix multiplication example













Below is the source code of the Java Program to Perform Matrix Multiplication,

MatrixMultiplication.java,

package com.example.demo;

public class MatrixMultiplication {
 
        public static void main(String[] args) {
  
                int a[][] = {{1,2,3},{4,5,6},{7,8,9}};    
  
                int b[][] = {{1,2,3},{4,5,6},{7,8,9}};    
      
                int c[][] = new int[3][3];  //rows - 3 and columns -3 
      
                for (int i = 0; i < 3; i++) {    
   
                       for (int j = 0; j < 3; j++) {    
    
                                 c[i][j] = 0;      
    
                                 for (int k = 0; k < 3; k++) {      
     
                                       c[i][j]+= a[i][k]*b[k][j];      
    
                                 } 
    
                                 System.out.print(c[i][j]+" ");   
                         } 
   
                        System.out.println(); 
                }    
        }
}
Output:--
30 36 42 
66 81 96 
102 126 150


Related Posts:--
1) Java code to move all zero of an integer array to the end of the array
2) Write a Java program to print the Floyd's triangle
3) Java Code to Print the Numbers as Pyramid - Examples
4) Java Program to find the Missing Number in an Array
5) Java program to print the first n prime numbers
6) Difference between NoClassDefFoundError and ClassNotFoundException in Java
7) Swap two variables without using third variable in Java
8) Java program to find second largest number in an array
9) Sort a binary array using one traversal in Java

1 comment: