Finding the matrix entrywise sum using element-wise addition.
Here’s a Java code example that finds the matrix entrywise sum using element-wise addition:
public class MatrixEntrywiseSum { 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[][] sumMatrix = getEntrywiseSum(matrix1, matrix2); // Print the sumMatrix for (int i = 0; i < sumMatrix.length; i++) { for (int j = 0; j < sumMatrix[i].length; j++) { System.out.print(sumMatrix[i][j] + " "); } System.out.println(); } } public static int[][] getEntrywiseSum(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] sumMatrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } return sumMatrix; } }
In this code, we have two matrices, `matrix1` and `matrix2`. The `getEntrywiseSum` method takes these two matrices as input and calculates the entrywise sum by adding the corresponding elements from each matrix. The resulting sum matrix is then returned.
The `main` method demonstrates the usage by creating two example matrices, calling the `getEntrywiseSum` method, and printing the resulting sum matrix. In this case, the output would be:
10 10 10
10 10 10
10 10 10
Each element of the sum matrix is obtained by adding the corresponding elements from `matrix1` and `matrix2`.
No comments yet! You be the first to comment.