Matrix Multiplicatin

In this article we are going to write A java code for mulitply two matrices. We will ask user to enter the both matrices and after that we perform matrix multiplicatio and print the result.

Matrix Multiplication Condition

For performig matrix multiplication no of column in first matrix should be equal to the no of rows in second matrix. If this condition is not satisfied then we can’t perform matrix multiplication

Java code for Matrix Multiplication

Steps for Java Multiplication Code

  • Take both matrix input from user
  • check if matrix multiplication condition is satisfied or not , if condition is not satisfied then exit from the program
  • else
  • mulitply both matrices using 2 for using 3 for loop (check in the code)
  • print the result matrix

Matrix multiplication Java Code

matrix_multiplication.java

package learn;
import java.util.*;
public class mtrix_multiplication {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the number of row in matrix1");
		int n1 = sc.nextInt();
		
		System.out.println("Enter the number of column in matrix1");
		int m1 = sc.nextInt();
		
		System.out.println("Enter the number of row in matrix2");
		int n2 = sc.nextInt();
		
		System.out.println("Enter the number of column in matrix2");
		int m2 = sc.nextInt();
		
		// checking matrix multiplication condition
		if(m1!=n2) {
			System.out.println(" Matrix multiplication is not possible");
			
		}
		else {
			
			int[][] matrix1 = new int[n1][m1];
			int[][] matrix2 = new int[n2][m2];
			
			System.out.println("Enter the matrix1");
			for(int i=0;i<n1;i++) {
				for(int j=0;j<m1;j++) {
					matrix1[i][j] = sc.nextInt();
				}
			}
			
			
			System.out.println("Enter the matrix2");
			for(int i=0;i<n2;i++) {
				for(int j=0;j<m2;j++) {
					matrix2[i][j] = sc.nextInt();
				}
			}
			
			// declaring 2d array for storing result of matrix multiplication
		
			int[][] multiplication = new int[n1][m2];
			
			// Performing matrix multiplication
			
			for(int i=0;i<n1;i++) {
				for(int j=0;j<m2;j++) {
					for(int k=0;k<n2;k++) {
						multiplication[i][j] += matrix1[i][k]* matrix2[k][j];
					}
				}
			}
			
			// printing resultant matrix
			for(int i=0;i<n1;i++) {
				for(int j=0;j<m2;j++) {
				System.out.print(multiplication[i][j]+" ");
				}
			System.out.println();
			}
		}
		
	}
}
		

matrix_multiplication.java Output

matrix multiplication

Here the output is for two (2*2) matrix multiplication but youxan enter any matrix of any dimension and perform matrix multiplication if matrix multiplication conditon is satisified.

Similar Java Tutorial (Matrix Progrram in Java)

Multidimensional Array in Java – https://gangforcode.com/multidimensional-array-in-java/
Matrix Addition in Java – https://gangforcode.com/matrix-addition-in-java/

1 thought on “Matrix Multiplicatin”

Leave a Comment