Java Matrix Addition Program (Add Two Matrices): 3 Ways
Matrices are fundamental mathematical structures used in various fields, including mathematics, physics, computer science, and engineering. In computer programming, matrices find extensive applications in tasks such as image processing, scientific simulations, and data analysis.
One common operation performed on matrices is addition, which involves adding corresponding elements of two matrices to create a new matrix.
In this tutorial, we will learn about the addition of two matrices in Java. We will walk you through the step-by-step process of creating a Java program that can take two matrices as input, add them together, and produce the resulting matrix as output.
Concepts Used:
Addition of Matrix in Java Using Scanner & Nested Loops
Here's a Java program to add two matrices using scanner and nested loops (with user input):
Code
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input matrix dimensions
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
// Initialize matrices
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
int[][] sum = new int[rows][columns];
// Input elements for the first matrix
System.out.println("Enter elements for the first matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = input.nextInt();
}
}
// Input elements for the second matrix
System.out.println("Enter elements for the second matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = input.nextInt();
}
}
// Perform matrix addition
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display the result
System.out.println("Sum of the matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
input.close();
}
}
Output
Enter the number of rows: 3
Enter the number of columns: 3
Enter elements for the first matrix:
3 2 5 2 6 1 2 1 3
Enter elements for the second matrix:
4 2 1 2 2 3 1 4 2
Sum of the matrices:
7 4 6
4 8 4
3 5 5
Explanation
The program first takes input for the dimensions (number of rows and columns) of the matrices.
Then, it initializes three 2D arrays: matrix1, matrix2, and sum, to store the input matrices and the result matrix, respectively.
The user enters the elements for both matrices.
Using nested loops, the program adds corresponding elements of matrix1 and matrix2 and stores the result in the sum matrix.
Finally, it displays the sum of the matrices by iterating through the sum matrix.
Addition of Two Matrices in Java Using Stream
Here's a Java program to add two matrices using streams and lambdas (Java 8 and later):
Code
import java.util.Arrays;
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input matrix dimensions
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
// Initialize matrices
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
// Input elements for the first matrix
System.out.println("Enter elements for the first matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = input.nextInt();
}
}
// Input elements for the second matrix
System.out.println("Enter elements for the second matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = input.nextInt();
}
}
// Perform matrix addition using streams and lambdas
int[][] sum = Arrays.stream(matrix1)
.map(row -> IntStream.range(0, row.length)
.mapToObj(col -> matrix2[row][col] + matrix1[row][col])
.toArray())
.toArray(int[][]::new);
// Display the result
System.out.println("Sum of the matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
input.close();
}
}
Output
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements for the first matrix:
1 2
3 4
Enter elements for the second matrix:
5 6
7 8
Sum of the matrices:
6 8
10 12
Explanation
Similar to the previous method, the program first takes input for the dimensions (number of rows and columns) of the matrices and initializes matrix1 and matrix2.
The user enters the elements for both matrices.
Matrix addition is performed using Java streams and lambdas. We use Arrays.stream() to stream the rows of matrix1. For each row, we use IntStream.range(0, row.length) to create an index range for columns.
Then, we use mapToObj to apply the addition operation to corresponding elements of both matrices and store the result in an array.
The resulting arrays from each row are collected into a 2D array sum using .toArray(int[][]::new).
Addition of Two Matrix in Java Using Parallel Processing
Here's a Java program to add two matrices using scanner and parallel processing (Java 8 and later):
Code
import java.util.Scanner;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class MatrixAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input matrix dimensions
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
// Initialize matrices
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
// Input elements for the first matrix
System.out.println("Enter elements for the first matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = input.nextInt();
}
}
// Input elements for the second matrix
System.out.println("Enter elements for the second matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = input.nextInt();
}
}
// Perform matrix addition using parallel processing
int[][] sum = new int[rows][columns];
MatrixAdditionTask task = new MatrixAdditionTask(matrix1, matrix2, sum, 0, 0, rows, columns);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(task);
// Display the result
System.out.println("Sum of the matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
input.close();
}
}
class MatrixAdditionTask extends RecursiveAction {
private static final int THRESHOLD = 100;
private int[][] matrix1;
private int[][] matrix2;
private int[][] sum;
private int startRow;
private int startCol;
private int rows;
private int cols;
public MatrixAdditionTask(int[][] matrix1, int[][] matrix2, int[][] sum, int startRow, int startCol, int rows, int cols) {
this.matrix1 = matrix1;
this.matrix2 = matrix2;
this.sum = sum;
this.startRow = startRow;
this.startCol = startCol;
this.rows = rows;
this.cols = cols;
}
@Override
protected void compute() {
if (rows <= THRESHOLD || cols <= THRESHOLD) {
// If the matrices are small, perform the addition sequentially
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[startRow + i][startCol + j] = matrix1[startRow + i][startCol + j] + matrix2[startRow + i][startCol + j];
}
}
} else {
// Split the task into smaller subtasks
int midRow = rows / 2;
int midCol = cols / 2;
MatrixAdditionTask[] tasks = {
new MatrixAdditionTask(matrix1, matrix2, sum, startRow, startCol, midRow, midCol),
new MatrixAdditionTask(matrix1, matrix2, sum, startRow, startCol + midCol, midRow, cols - midCol),
new MatrixAdditionTask(matrix1, matrix2, sum, startRow + midRow, startCol, rows - midRow, midCol),
new MatrixAdditionTask(matrix1, matrix2, sum, startRow + midRow, startCol + midCol, rows - midRow, cols - midCol)
};
// Fork and join the subtasks
invokeAll(tasks);
}
}
}
Output
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements for the first matrix:
1 2 3 4
Enter elements for the second matrix:
4 3 2 1
Sum of the matrices:
5 5
5 5
Explanation
Similar to the previous methods, the program first takes input for the dimensions (number of rows and columns) of the matrices and initializes matrix1 and matrix2.
The user enters the elements for both matrices.
Matrix addition is performed using parallel processing with the help of the MatrixAdditionTask class. The matrices are split into smaller submatrices, and addition is performed concurrently using Fork-Join framework.
Finally, it displays the sum of the matrices by iterating through the sum matrix, which contains the result. This method allows for efficient parallel processing of matrix addition for large matrices.
Learn Next: