Finding the matrix entrywise difference using element-wise subtraction.
Here’s a Java program that calculates the element-wise difference between two matrices using subtraction:
public class MatrixDifference { 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[][] difference = calculateMatrixDifference(matrix1, matrix2); // Print the resulting difference matrix System.out.println("Matrix Difference:"); printMatrix(difference); } public static int[][] calculateMatrixDifference(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] difference = new int[rows][columns]; // Calculate the element-wise difference using subtraction for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { difference[i][j] = matrix1[i][j] - matrix2[i][j]; } } return difference; } public static void printMatrix(int[][] matrix) { int rows = matrix.length; int columns = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
In this program, we have two matrices `matrix1` and `matrix2` with the same dimensions. The method `calculateMatrixDifference` takes these two matrices as inputs and returns the resulting difference matrix. It subtracts each corresponding element from `matrix1` and `matrix2` and stores the result in the `difference` matrix.
Finally, the program prints the resulting difference matrix using the `printMatrix` method.
No comments yet! You be the first to comment.