# How To Subtract Two Matrices in Java

Matrix operations are important in a number of programming problems in the areas of image processing, probability theory and physics simulation. Matrix subtraction is simple, and it involves subtracting each entry in the second matrix from the corresponding entry in the first matrix.

The following Java program demonstrates matrix subtraction. This example uses constant matrices hard-coded in Java, but you can easily change getMatrixA or getMatrixB to read them from files or from command line. Also note how we derive number of rows and columns from the data.

```/**
* Demonstrates matrix subtraction in java
*/
public class MatrixSubtraction {

public static void main(String[] args) {
MatrixSubtraction ms = new MatrixSubtraction();
ms.subtractMatrices();
}

/**
* Gets two matrices, subtracts them and prints the result on console.
*/
private void subtractMatrices() {
int[][] matrixA = getMatrixA();
int[][] matrixB = getMatrixB();

int[][] matrixResult = subtractMatrices(matrixA, matrixB);
printMatrix(matrixResult);
}

/**
* Returns first matrix
* @return
*/
private int[][] getMatrixA() {
int[][] matrixA = new int[][] {
{8,2,4},
{5,2,9}

};
return matrixA;
}

/**
* Returns second matrix
* @return
*/
private int[][] getMatrixB() {
int[][] matrixB = new int[][] {
{7,1,3},
{4,1,8}

};
return matrixB;
}

//Subtracts two matrices.
private int[][] subtractMatrices(int[][] matrixA, int[][] matrixB) {
int rows=matrixA.length;
int cols=matrixA[0].length;

int[][] sum = new int[rows][cols];
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
sum[i][j] = matrixA[i][j] - matrixB[i][j];
}
}
return sum;
}

/**
* Prints the matrix on command line.
* @param matrix
*/
public void printMatrix(int[][] matrix) {
int rows=matrix.length;
int cols=matrix[0].length;

for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
System.out.print(" "+matrix[i][j]);
}
System.out.println();
}
}
}```