When you subtract two matrices subtraction is done index wise you subtract the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

**As example** – If you are subtracting two matrices of order 3X3 -

Which results in -

Also remember these points when subtracting one matrix with another -

- Both of the matrix have to be of same size.
- Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix minus (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

__Matrix subtraction Java program__

import java.util.Scanner; public class MatrixSubtraction { public static void main(String[] args) { int rowM, colM; Scanner in = new Scanner(System.in); System.out.print("Enter Number of Rows and Columns of Matrix : "); rowM = in.nextInt(); colM = in.nextInt(); int M1[][] = new int[rowM][colM]; int M2[][] = new int[rowM][colM]; int resMatrix[][] = new int[rowM][colM]; System.out.print("Enter elements of First Matrix : "); for(int i = 0; i < rowM; i++){ for(int j = 0; j < colM; j++){ M1[i][j] = in.nextInt(); } } System.out.println("First Matrix : " ); for(int i = 0; i < rowM; i++){ for(int j = 0; j < colM; j++){ System.out.print(" " +M1[i][j]+"\t"); } System.out.println(); } System.out.print("Enter elements of Second Matrix : "); for(int i = 0; i < rowM; i++){ for(int j = 0; j < colM; j++){ M2[i][j] = in.nextInt(); } } System.out.println("Second Matrix : " ); for(int i = 0; i < rowM; i++){ for(int j = 0; j < colM; j++){ System.out.print(" " +M2[i][j] + "\t"); } System.out.println(); } // Subtraction logic for(int i = 0; i < rowM; i++){ for(int j = 0; j < colM; j++){ resMatrix[i][j] = M1[i][j] - M2[i][j]; } } // Printing the result matrix System.out.println("Result Matrix : " ); for(int i = 0; i < resMatrix.length; i++){ for(int j = 0; j < colM; j++){ System.out.print(" " +resMatrix[i][j]+"\t"); } System.out.println(); } } }

__Output__

Enter Number of Rows and Columns of Matrix : 3 3 Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2 First Matrix : 1 3 4 2 5 6 4 3 2 Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1 Second Matrix : 2 7 1 0 4 6 9 8 1 Result Matrix : -1 -4 3 2 1 0 -5 -5 1

That's all for this topic **Matrix Subtraction - Java Program**. If you have any doubt or any
suggestions to make please drop a comment. Thanks!

__Related Topics__

**You may also like - **

ReplyDeleteI saw lot of information On Other Site But this blog helped me alot to learn Java Thanks for sharing.........