Java Matrix Multiplication Program (Multiply Two Matrices)
Matrix multiplication is a fundamental operation in linear algebra and plays a crucial role in various fields, including computer graphics, machine learning, and scientific computing. You can efficiently implement matrix multiplication in Java using loops and arrays.
This tutorial will guide you through the process of creating a Java program to multiply two matrices step by step.
Matrix multiplication involves taking the dot product of rows and columns to generate a new matrix. Each element of the resulting matrix is calculated by multiplying elements from the corresponding row of the first matrix and the corresponding column of the second matrix and then summing these products.
Concepts to Learn:
Multiplication of Matrices in Java Using Nested Loops
Here's a program to multiply two matrices in Java using nested loops:
Code
public class MatrixMultiplication {
public static void main(String[] args) {
// Define two matrices
int[][] firstMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] secondMatrix = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
// Initialize the result matrix
int[][] resultMatrix = new int[firstMatrix.length][secondMatrix[0].length];
// Multiply matrices
for (int i = 0; i < firstMatrix.length; i++) {
for (int j = 0; j < secondMatrix[0].length; j++) {
for (int k = 0; k < secondMatrix.length; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
// Display the result
System.out.println("Result Matrix:");
for (int i = 0; i < resultMatrix.length; i++) {
for (int j = 0; j < resultMatrix[0].length; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
Output
firstMatrix:
1 2 3
4 5 6
7 8 9
secondMatrix:
9 8 7
6 5 4
3 2 1
Result Matrix:
30 24 18
84 69 54
138 114 90
Explanation
-
We define two matrices, firstMatrix and secondMatrix, as 2D arrays.
-
We initialize an empty resultMatrix with the dimensions of the resulting matrix.
-
Using nested loops, we calculate each element of the resultMatrix by multiplying elements from the corresponding rows of the first matrix and columns of the second matrix.
- Finally, we display the resultMatrix, which is the product of the two input matrices.
Matrix Multiplication in Java Using Scanner
Here's a program for multiplication of two matrices using the Scanner class for input:
Code
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows for the first matrix: ");
int rowsA = input.nextInt();
System.out.print("Enter the number of columns for the first matrix: ");
int colsA = input.nextInt();
System.out.print("Enter the number of rows for the second matrix: ");
int rowsB = input.nextInt();
System.out.print("Enter the number of columns for the second matrix: ");
int colsB = input.nextInt();
if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible. Number of columns in the first matrix must be equal to the number of rows in the second matrix.");
input.close();
return;
}
int[][] firstMatrix = new int[rowsA][colsA];
int[][] secondMatrix = new int[rowsB][colsB];
System.out.println("Enter the elements of the first matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
firstMatrix[i][j] = input.nextInt();
}
}
System.out.println("Enter the elements of the second matrix:");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
secondMatrix[i][j] = input.nextInt();
}
}
input.close();
// Check if multiplication is possible and multiply matrices
if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible.");
} else {
int[][] resultMatrix = multiplyMatrices(firstMatrix, secondMatrix);
// Display the result
System.out.println("Result Matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix) {
int rowsA = firstMatrix.length;
int colsA = firstMatrix[0].length;
int colsB = secondMatrix[0].length;
int[][] resultMatrix = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
return resultMatrix;
}
}
Output
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter the number of rows for the second matrix: 2
Enter the number of columns for the second matrix: 2
Enter the elements of the first matrix:
3 5 6 1
Enter the elements of the second matrix:
1 3 2 4
Result Matrix:
13 29 8 22
Explanation
-
We use the Scanner class to take input from the user for the dimensions and elements of the two matrices.
-
We check if matrix multiplication is possible by comparing the number of columns in the first matrix to the number of rows in the second matrix.
-
If multiplication is possible, we create the matrices, input their elements, and then multiply them using the multiplyMatrices function, similar to the first method explained earlier.
-
Finally, we display the resulting matrix.
Java Program to Multiply Two Matrices Using Thread
Multiplying matrices using threads can help improve performance by parallelizing the calculation. Here's a Java program to multiply two matrices using threads:
Code
class MatrixMultiplier extends Thread {
private int[][] matrixA;
private int[][] matrixB;
private int[][] resultMatrix;
private int row;
public MatrixMultiplier(int[][] matrixA, int[][] matrixB, int[][] resultMatrix, int row) {
this.matrixA = matrixA;
this.matrixB = matrixB;
this.resultMatrix = resultMatrix;
this.row = row;
}
@Override
public void run() {
for (int i = 0; i < matrixB[0].length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
resultMatrix[row][i] += matrixA[row][j] * matrixB[j][i];
}
}
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int rowsA = matrixA.length;
int colsA = matrixA[0].length;
int colsB = matrixB[0].length;
if (colsA != matrixB.length) {
System.out.println("Matrix multiplication is not possible. Number of columns in the first matrix must be equal to the number of rows in the second matrix.");
return;
}
int[][] resultMatrix = new int[rowsA][colsB];
MatrixMultiplier[] threads = new MatrixMultiplier[rowsA];
// Create and start threads
for (int i = 0; i < rowsA; i++) {
threads[i] = new MatrixMultiplier(matrixA, matrixB, resultMatrix, i);
threads[i].start();
}
// Wait for all threads to finish
try {
for (int i = 0; i < rowsA; i++) {
threads[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Display the result matrix
System.out.println("Result Matrix:");
for (int[] row : resultMatrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Output
matrixA:
1 2 3
4 5 6
7 8 9
matrixB:
9 8 7
6 5 4
3 2 1
Result Matrix:
30 24 18
84 69 54
138 114 90
Explanation
-
The program defines a MatrixMultiplier class that extends Thread. Each thread is responsible for calculating a specific row of the result matrix.
-
We create an array of threads, one for each row of the result matrix, and start them concurrently.
-
Each thread calculates its assigned row of the result matrix by iterating through the columns of the result matrix and performing the matrix multiplication.
-
After all threads have finished their calculations, we join them to ensure that the main thread waits for all threads to complete.
-
Finally, we display the resulting matrix.
Java Matrix Multiplication Program Using Streams
Here's a program for multiplication of matrix in Java using Streams:
Code
import java.util.Arrays;
import java.util.stream.IntStream;
public class MatrixMultiplication {
public static void main(String[] args) {
// Define two matrices
int[][] firstMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] secondMatrix = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
// Calculate the result matrix using Java Streams
int[][] resultMatrix = multiplyMatrices(firstMatrix, secondMatrix);
// Display the result
System.out.println("Result Matrix:");
for (int[] row : resultMatrix) {
System.out.println(Arrays.toString(row));
}
}
public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix) {
int rowsA = firstMatrix.length;
int colsA = firstMatrix[0].length;
int colsB = secondMatrix[0].length;
return IntStream.range(0, rowsA)
.mapToObj(i -> IntStream.range(0, colsB)
.map(j -> IntStream.range(0, colsA)
.map(k -> firstMatrix[i][k] * secondMatrix[k][j])
.sum())
.toArray())
.toArray(int[][]::new);
}
}
Output
firstMatrix:
1 2 3
4 5 6
7 8 9
secondMatrix:
9 8 7
6 5 4
3 2 1
Result Matrix:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
Explanation
-
We define two matrices, firstMatrix and secondMatrix, as 2D arrays.
-
We use Java Streams to calculate the result matrix by performing matrix multiplication in a more concise and functional style.
-
The multiplyMatrices function takes the two input matrices and uses streams to compute each element of the resulting matrix.
-
The IntStream range is used to iterate over rows and columns, and for each element in the result matrix, we calculate the dot product of the corresponding rows and columns of the input matrices.
-
The result is stored in the resultMatrix.
Multiplication of Two Matrix in Java Using Apache Commons Math
Here's a Java program to multiply two matrices using an external library, Apache Commons Math:
Note: To use Apache Commons Math, you need to include the library in your project.
Code
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
public class MatrixMultiplication {
public static void main(String[] args) {
// Define two matrices
double[][] firstMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
double[][] secondMatrix = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
// Create RealMatrix objects from the arrays
RealMatrix matrixA = MatrixUtils.createRealMatrix(firstMatrix);
RealMatrix matrixB = MatrixUtils.createRealMatrix(secondMatrix);
// Multiply matrices using Apache Commons Math
RealMatrix resultMatrix = matrixA.multiply(matrixB);
// Display the result
double[][] resultArray = resultMatrix.getData();
System.out.println("Result Matrix:");
for (double[] row : resultArray) {
for (double element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Output
firstMatrix:
1 2 3
4 5 6
7 8 9
secondMatrix:
9 8 7
6 5 4
3 2 1
Result Matrix:
30.0 24.0 18.0
84.0 69.0 54.0
138.0 114.0 90.0
Explanation
-
We define two matrices, firstMatrix and secondMatrix, as 2D arrays.
-
We use Apache Commons Math, an external library, to perform matrix multiplication.
-
We create RealMatrix objects from the input arrays using MatrixUtils.createRealMatrix.
-
We use the multiply method to multiply the two matrices and store the result in a RealMatrix.
-
We extract the resulting matrix as a 2D array and display it.
Learn Next: