Matrix subtraction.
Here’s an example program in Java that performs matrix subtraction:
import java.util.Arrays; public class MatrixSubtraction { 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[][] result = subtractMatrices(matrix1, matrix2); System.out.println("Matrix1:"); printMatrix(matrix1); System.out.println("Matrix2:"); printMatrix(matrix2); System.out.println("Subtraction Result:"); printMatrix(result); } public static int[][] subtractMatrices(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int columns = matrix1[0].length; int[][] result = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { result[i][j] = matrix1[i][j] - matrix2[i][j]; } } return result; } public static void printMatrix(int[][] matrix) { for (int[] row : matrix) { System.out.println(Arrays.toString(row)); } System.out.println(); } }
In this program, the `subtractMatrices` function takes two matrices as input and returns their subtraction. The `printMatrix` function is used to display the matrices.
The program creates two matrices `matrix1` and `matrix2` and performs subtraction using the `subtractMatrices` function. It then displays the original matrices and the subtraction result.
When you run this program, the output will be:
Matrix1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix2:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Subtraction Result:
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]
This demonstrates matrix subtraction, where each corresponding element of the two matrices is subtracted to obtain the result.
No comments yet! You be the first to comment.