Java Matrix Multiplication Example


 

Java Matrix Multiplication Example

In this tutorial, you will learn how to multiply two matrices.

In this tutorial, you will learn how to multiply two matrices.

Java Matrix Multiplication Example

In this tutorial, you will learn how to multiply two matrices.

Like mathematical operations of two numbers, you can perform these operations on matrices too. Here we are going to calculate the multiplication of two matrices of any order. In the given program, firstly we have allowed the user to enter the number of rows and columns to show in matrices and then accept the matrix elements as array elements. We have declared two 2-dimensional array of integer type to store the matrix elements. Now to find the multiplication of two matrices, we have performed following distinctive steps( for loops ):


	for(int i = 0; i < A.length; i++): this loop controls the row position
	for(int j = 0; j < B[0].length; j++): this loop controls the column position
	for(int k = 0; k < A[0].length; k++): controls the index of which individual cell is being multiplied and added up.
    

Example:

import java.util.*;
class MatrixMultiplication{

public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter Number of rows: ");
int m = input.nextInt();

System.out.print("Enter Number of columns: ");
int n = input.nextInt();

int[][] A = new int[m][n];
int[][] B = new int[m][n];
int[][] C = new int[m][n];
System.out.println("Enter elements for matrix A : ");
for (int i=0 ; i < A.length ; i++)
for (int j=0 ; j < A[i].length ; j++){
A[i][j] = input.nextInt();
}
System.out.println("Enter elements for matrix B : ");
for (int i=0 ; i < B.length ; i++)
for (int j=0 ; j < B[i].length ; j++){
B[i][j] = input.nextInt();
}
System.out.println("Matrix A: ");
for (int i=0 ; i < A.length ; i++){
System.out.println();
for (int j=0 ; j < A[i].length ; j++){
System.out.print(A[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Matrix B: ");
for(int i=0 ; i < B.length ; i++){ 
System.out.println();
for (int j=0 ; j < B[i].length ; j++){
System.out.print(B[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Result is: ");
System.out.println();

for(int i=0;i<A.length;i++){
for(int j=0;j<B[0].length;j++){
for(int k=0;k<A[0].length;k++){
C[i][j]+=A[i][k]*B[k][j];
}
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(+C[i][j]+" ");
}
System.out.println();
} 
}
}

Output:

Enter Number of rows: 3
Enter Number of columns: 3
Enter elements for matrix A :
1
2
3
1
2
3
1
2
3
Enter elements for matrix B :
1
2
3
1
2
3
1
1
1
Matrix A:

1 2 3
1 2 3
1 2 3

Matrix B:

1 2 3
1 2 3
1 1 1

Result is:

6 9 12
6 9 12
6 9 12

Ads