Perform Matrix Subtraction in Java
What you’ll learn
- The element-wise rule
Cij = Aij − Bijfor matrices of the same size. - A complete 3×3 Java program (including negative differences), a compact 2×2 variant, and a live preview.
- How subtraction relates to addition (
A − B = A + (−B)) and common interview follow-ups.
Overview
Subtracting matrices works like subtracting numbers in a table: each cell in A is subtracted by the matching cell in B.
Two programs
3×3 reference data and a 2×2 difference.
Live preview
Same integers as example 1; prints A, B, and A − B.
Negatives
Expect negative entries whenever B is greater than A in a cell.
Prerequisites
2D arrays, nested loops, and same-size matrix checks.
- 2D arrays and nested loops in Java.
- Both matrices must have the same dimensions.
What is matrix subtraction?
For same-sized matrices, subtract each matching cell: C[i][j] = A[i][j] - B[i][j]. Order matters: A - B is not equal to B - A.
Definition
(A - B)[i][j] = A[i][j] - B[i][j] (entry-wise subtraction).
Intuition
Subtract each matching cell; signs can become negative.
Live preview
Uses the same 3x3 sample matrices from Example 1.
Algorithm
Goal: compute C[i][j] = A[i][j] - B[i][j] for every cell.
Same shape
A and B must have the same rows and columns.
Subtract per cell
Use nested loops for i and j, then assign result[i][j] = a[i][j] - b[i][j].
Display
Print each row in a clean format so output is easy to read.
📜 Pseudocode
function subtractMatrices(A, B, C, rows, cols):
for i from 0 to rows - 1:
for j from 0 to cols - 1:
C[i][j] = A[i][j] - B[i][j]Subtract two 3×3 matrices
subtractMatrices computes matrix1 - matrix2. Some cells become negative, which is normal.
public class Main {
static void subtractMatrices(int[][] mat1, int[][] mat2, int[][] result) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}
static void displayMatrix(int[][] matrix) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix1 = {
{5, 8, 2},
{7, 4, 9},
{3, 6, 1}
};
int[][] matrix2 = {
{3, 1, 7},
{6, 9, 2},
{8, 5, 4}
};
int[][] resultMatrix = new int[3][3];
subtractMatrices(matrix1, matrix2, resultMatrix);
System.out.println("Matrix 1:");
displayMatrix(matrix1);
System.out.println("\nMatrix 2:");
displayMatrix(matrix2);
System.out.println("\nResultant Matrix (Matrix1 - Matrix2):");
displayMatrix(resultMatrix);
}
}Subtract two 2×2 matrices
A compact version for quick interview explanation.
public class Main {
static final int ROWS = 2;
static final int COLS = 2;
static void subtractMatrices(int[][] a, int[][] b, int[][] out) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
out[i][j] = a[i][j] - b[i][j];
}
}
}
static void printMatrix(String title, int[][] m) {
System.out.println(title);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = {
{1, 2},
{3, 4}
};
int[][] b = {
{4, 3},
{2, 1}
};
int[][] c = new int[ROWS][COLS];
subtractMatrices(a, b, c);
printMatrix("A", a);
System.out.println();
printMatrix("B", b);
System.out.println();
printMatrix("A - B", c);
}
}Optimization note
Time is already optimal at O(m*n) because each output cell must be written once.
❓ FAQ
🔄 Input / output examples
For A=[[1,2],[3,4]] and B=[[4,3],[2,1]], output is [[-3,-1],[1,3]].
Edge cases
Reject mismatch
Subtraction is valid only when rows and columns are equal in both matrices.
Integer overflow
Use long if values are very large and may exceed int.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Subtract two m × n matrices | O(m · n) | O(1) besides result storage |
Summary
- Matrix subtraction is entry-wise and requires equal shapes.
- Nested loops produce
O(m*n)time and constant extra space (excluding output matrix).
Matrix subtraction is entrywise like addition: (A − B)ij = Aij − Bij. It is the same as adding A and (−B). The two matrices must have the same shape.
8 people found this page helpful
