Finding the entrywise sum of two matrices.
Here’s a Java program that finds the entrywise sum of two matrices:
import java.util.Arrays; public class MatrixSum { public static void main(String[] args) { int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int[][] sum = findMatrixSum(matrix1, matrix2); System.out.println("Matrix 1:"); printMatrix(matrix1); System.out.println("Matrix 2:"); printMatrix(matrix2); System.out.println("Sum:"); printMatrix(sum); } public static int[][] findMatrixSum(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] sum = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { sum[i][j] = matrix1[i][j] + matrix2[i][j]; } } return sum; } public static void printMatrix(int[][] matrix) { for (int[] row : matrix) { System.out.println(Arrays.toString(row)); } System.out.println(); } }
This program defines a `findMatrixSum` function that takes two matrices as input and returns their entrywise sum. The `main` function demonstrates the usage of this function by creating two matrices, finding their sum, and printing the matrices and their sum to the console. The `printMatrix` function is a helper function used to print the matrices in a readable format.
When you run this program, it will output:
Matrix 1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix 2:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Sum:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
In the sum matrix, each element is the sum of the corresponding elements from matrix 1 and matrix 2.
No comments yet! You be the first to comment.