Matrix Multiplication Example Java Program

Definition

A matrix (plural matrices) is a rectangular array of numbers, symbols, or expressions, arranged in rows and columns that is treated in certain prescribed ways. matrix multiplication is a binary operation that takes a pair of matrices, and produces another matrix. Numbers such as the real or complex numbers can be multiplied according to elementary arithmetic. if A is an n × m matrix and B is an m × p matrix, their matrix product AB is an n × p matrix, in which the m entries across the rows of A are multiplied with the m entries down the columns of B.

Matrix Multiplication Example Program

import java.util.Scanner;
class MatrixMultiplication{
	public static void main(String args[]){
		int mat1[][]=new int[3][3];
		int mat2[][]=new int[3][3];
		int mat3[][]=new int[3][3];
		System.out.println("Enter the first (3*3) matrix:");
		Scanner input=new Scanner(System.in);
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++)}
			    mat1[i][j]=input.nextInt();
			}
			System.out.println("Enter the second (3*3) matrix:");
		}
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				mat2[i][j]=input.nextInt();
			}
			System.out.println("The two matrices to be multiplied are as follows:");
		}
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				mat3[i][j]=0;
				for(int k=0;k<3;k++){
				  mat3[i][j]+=mat1[i][k]*mat2[k][j];
	           	}
			}
	    }
	    for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
	     		System.out.print(mat1[i][j]+"\t");
    		}
    		System.out.println("\n");
        }
       	System.out.println("\n");
        for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
	     		System.out.print(mat2[i][j]+"\t");
    		}
    		System.out.println("\n");
        }	
        System.out.println("\n");
		System.out.println("The matrix after multiplication is as follows");
	    for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
	     		System.out.print(mat3[i][j]+"\t");
    		}
    		System.out.println("\n");
        }		   	
	}
}

Sample Output

Output is:
Enter the first (3*3) matrix:
6
7
3
8
3
2
76
4
2
Enter the second (3*3) matrix:
0
3
7
2
5
1
2
7
8
The two matrices to be multiplied are as follows:
6       7       3

8       3       2

76      4       2



0       3       7

2       5       1

2       7       8



The matrix after multiplication is as follows
20      74      73

10      53      75

12      262     552