This post shows a Java program to subtract two matrices.

When you subtract two matrices you subtract the element at the same index in both matrices so you’ll subtract the element at index (0, 0) in the first matrix with the element at index (0, 0) in the second matrix to get the element at (0, 0) in the resultant matrix. Also note that both of the matrix have to be of the same order for subtraction.

**For example** – If you are subtracting two 3 X 3 matrices.

#### Java program for matrix subtraction

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.Scanner; public class MatrixSubtraction { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter number of rows and columns in the matrix : "); int row = in.nextInt(); int column = in.nextInt(); // First matrix int[][] matrix1 = prepareMatrix(row, column); // Second matrix int[][] matrix2 = prepareMatrix(row, column); // Subtraction result stored in this matrix int subtractMatrix[][] = new int[row][column]; // Subtraction logic for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ subtractMatrix[i][j] = matrix1[i][j] - matrix2[i][j]; } } System.out.println("Subtracted Matrix : " ); for(int i = 0; i < subtractMatrix.length; i++){ for(int j = 0; j < column; j++){ System.out.print(" " +subtractMatrix[i][j]+"\t"); } System.out.println(); } } private static int[][] prepareMatrix(int row, int column){ Scanner sc = new Scanner(System.in); System.out.print("Enter elements of Matrix : "); int matrix[][] = new int[row][column]; for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ matrix[i][j] = sc.nextInt(); } } System.out.println("Entered Matrix : " ); for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ System.out.print(" " +matrix[i][j]+"\t"); } System.out.println(); } return matrix; } } |

__Output__

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Enter number of rows and columns in the matrix : 3 3 Enter elements of Matrix : 1 3 8 2 9 3 0 5 11 Entered Matrix : 1 3 8 2 9 3 0 5 11 Enter elements of Matrix : 0 2 4 6 7 8 2 3 5 Entered Matrix : 0 2 4 6 7 8 2 3 5 Subtracted Matrix : 1 1 4 -4 2 -5 -2 2 6 |

That’s all for the topic **Matrix Subtraction Java Program**. If something is missing or you have something to share about the topic please write a comment.

**You may also like**

- Matrix Multiplication Java Program
- How to Swap Two Numbers Without Using Third Variable
- CopyOnWriteArrayList in Java
- ThreadLocal Class in Java
- final in Java
- NameNode, Secondary Namenode and Datanode in HDFS