Finding the entrywise difference of two matrices
Here’s an example of a Java program that finds the entrywise difference of two matrices:
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 rows = matrix1.length; int cols = matrix1[0].length; int[][] difference = new int[rows][cols]; // Finding the difference of matrices for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { difference[i][j] = matrix1[i][j] - matrix2[i][j]; } } // Displaying the difference matrix System.out.println("Difference Matrix:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(difference[i][j] + " "); } System.out.println(); } } }
In this example, we have two matrices: `matrix1` and `matrix2`. The program calculates the entrywise difference by subtracting the corresponding elements of `matrix2` from `matrix1`. The resulting difference matrix is stored in the `difference` array. Finally, the program displays the difference matrix.
When you run this program, the output will be:
Difference Matrix:
-8 -6 -4
-2 0 2
4 6 8
This shows the entrywise difference of `matrix1` and `matrix2`.
No comments yet! You be the first to comment.