In this tutorial, we will learn how to matrix multiplication by using Java. For this matrix multiplication we will use the 2D in Java. It is one of the simple and the easiest problems to solve in the Java. By using this we can solve a lot complex problems. In this we are going to learn with a simple code in java.
The below is the code :
import java.util.Scanner; public class MatrixMultiplication { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Read the dimensions of the matrices System.out.print("Enter the number of rows for the first matrix: "); int rowA = input.nextInt(); System.out.print("Enter the number of columns for the first matrix: "); int colA = input.nextInt(); System.out.print("Enter the number of rows for the second matrix: "); int rowB = input.nextInt(); System.out.print("Enter the number of columns for the second matrix: "); int colB = input.nextInt(); // Check if matrix multiplication is possible if (colA != rowB) { System.out.println("Matrix multiplication is not possible."); return; } // Initialize matrices int[][] matrixA = new int[rowA][colA]; int[][] matrixB = new int[rowB][colB]; int[][] resultMatrix = new int[rowA][colB]; // Read elements of matrix A System.out.println("Enter the elements of matrix A:"); for (int i = 0; i < rowA; i++) { for (int j = 0; j < colA; j++) { matrixA[i][j] = input.nextInt(); } } // Read elements of matrix B System.out.println("Enter the elements of matrix B:"); for (int i = 0; i < rowB; i++) { for (int j = 0; j < colB; j++) { matrixB[i][j] = input.nextInt(); } } // Perform matrix multiplication for (int i = 0; i < rowA; i++) { for (int j = 0; j < colB; j++) { int sum = 0; for (int k = 0; k < colA; k++) { sum += matrixA[i][k] * matrixB[k][j]; } resultMatrix[i][j] = sum; } } // Display the result matrix System.out.println("\nResultant matrix (A * B):"); for (int i = 0; i < rowA; i++) { for (int j = 0; j < colB; j++) { System.out.print(resultMatrix[i][j] + " "); } System.out.println(); } } }
Here we can give the input of our own choice elements as we are using Scanner in this code.