Definition
Cij = Aij − Bij
Subtract corresponding entries when shapes match.
Matrix subtraction is the entry-by-entry difference of two matrices of identical shape: Cij = Aij − Bij. This tutorial covers the shape rule, nested loops, negatives in the result, a live preview, worked C examples (3×3 and 2×2), edge cases, and O(m·n) complexity.
Cij = Aij − Bij
Subtract corresponding entries when shapes match.
m × n
Identical rows and columns — same rule as addition.
i, then j
One subtraction per cell; no shared k dimension.
int signs
When B exceeds A in a cell, the difference is negative.
3×3 A−B
See both factors and the difference instantly.
≠ AB
Unlike multiplication, order of cells is entrywise only.
For matrices A and B of the same shape, matrix subtraction produces C = A − B where Cij = Aij − Bij for every row i and column j.
Equivalently, subtracting B is adding (−B) entrywise. In C interviews you write the same double nest as addition, swap + for -, and expect negatives.
It locks in the element-wise pattern after addition and before transpose — and quizzes whether you know order matters (A − B ≠ B − A).
Same indices in A and B.
Same rows and columns required.
B − A = −(A − B).
One pass over every entry.
In short: for each i,j set C[i][j] = A[i][j] - B[i][j] — same loops as addition, different operator.
Given two matrices of the same size, compute C = A − B entrywise and print the factors plus the difference.
/* A and B both 3×3 → C 3×3
* C[0][0] = 5 - 3 = 2
* C[0][2] = 2 - 7 = -5 (negatives are normal)
*/ | Item | Type | Description |
|---|---|---|
mat1, mat2 | 2D arrays | Operands; must share the same dimensions. |
result | 2D array | Difference; each cell is one subtraction. |
ROWS / COLS | macros | Shape for the generalized 2×2 sample. |
function subtract_matrices(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] | Operation | Rule | Loops |
|---|---|---|
| Subtraction (this page) | Aij − Bij | Double nest; same shape |
| Addition | Aij + Bij | Double nest; same shape |
| Matrix multiply | Row·column sums | Triple nest; inner sizes match |
| Goal | Pattern |
|---|---|
| One cell | result[i][j] = a[i][j] - b[i][j]; |
| Compatibility | rows(A) == rows(B) and cols(A) == cols(B) |
| Relation | A - B = A + (-B) entrywise |
| Reverse | B - A = -(A - B) |
| Cost | O(m · n) for m × n |
Related matrix operations — only subtraction and addition share the same double-loop shape rule.
Aij-BijThis page — element-wise
Aij+BijSame loops; swap the operator
Σ Aik BkjDifferent rules; triple nest
order!A−B ≠ B−A in general
Reach for matrix subtraction when comparing grids cell by cell or forming residuals.
Same structure as addition; tests negatives and order.
Difference between predicted and actual tables.
Conceptual cousin: subtract corresponding samples.
Clarify element-wise vs row·column products.
Refuse when dimensions differ.
Key benefit: one clear element-wise pattern that proves you understand shape rules and signed results.
Uses the same 3×3 integer matrices as Example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.
Two complete C programs — a classic 3×3 difference (with negatives) and a smaller 2×2 you can check by hand. Click View Output to reveal sample console results.
Double nest: one subtraction per matching cell.
subtract_matrices computes matrix1 − matrix2. Differences can be negative — that is expected.
#include <stdio.h>
void subtract_matrices(int mat1[3][3], int mat2[3][3], int result[3][3]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}
void display_matrix(int matrix[3][3]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main(void) {
int matrix1[3][3] = {
{5, 8, 2},
{7, 4, 9},
{3, 6, 1}
};
int matrix2[3][3] = {
{3, 1, 7},
{6, 9, 2},
{8, 5, 4}
};
int result_matrix[3][3];
subtract_matrices(matrix1, matrix2, result_matrix);
printf("Matrix 1:\n");
display_matrix(matrix1);
printf("\nMatrix 2:\n");
display_matrix(matrix2);
printf("\nResultant Matrix (Matrix1 - Matrix2):\n");
display_matrix(result_matrix);
return 0;
} Each result[i][j] is one subtraction. Tab spacing keeps columns readable in the terminal. Notice cells like 2 - 7 = -5 — signed int handles this naturally.
Same pattern with macros for rows and columns.
Useful when an interviewer asks for a smaller trace-by-hand example. Here 1 - 4 = -3 and 4 - 1 = 3.
#include <stdio.h>
#define ROWS 2
#define COLS 2
void subtract_matrices(int a[ROWS][COLS], int b[ROWS][COLS], int out[ROWS][COLS]) {
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
out[i][j] = a[i][j] - b[i][j];
}
}
}
void print_matrix(const char *title, int m[ROWS][COLS]) {
printf("%s\n", title);
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
printf("%d ", m[i][j]);
}
printf("\n");
}
}
int main(void) {
int a[ROWS][COLS] = {
{1, 2},
{3, 4}
};
int b[ROWS][COLS] = {
{4, 3},
{2, 1}
};
int c[ROWS][COLS];
subtract_matrices(a, b, c);
print_matrix("A", a);
printf("\n");
print_matrix("B", b);
printf("\n");
print_matrix("A - B", c);
return 0;
} ROWS / COLS make the shape easy to change. Negatives and positives appear together in one small grid.
Confirm A and B share row and column counts.
Nested loops over i and j; assign A[i][j] - B[i][j].
Optional helper to print each row on its own line.
For the 3×3 sample, top-left is 2; negatives like -5 appear where B wins.
Trace row 0 of Matrix1 − Matrix2.
| j | A[0][j] | B[0][j] | A − B |
|---|---|---|---|
0 | 5 | 3 | 2 |
1 | 8 | 1 | 7 |
2 | 2 | 7 | -5 |
So the first result row is 2 7 -5. Repeat the same pattern for every other row.
Where matrix-subtraction thinking shows up beyond the interview prompt.
Master 2D indexing with a simple operator.
Example: i, then j.
Compare expected vs actual entrywise.
Example: score or sensor grids.
Prove you handle negatives without panic.
Example: 3×3 sample output.
Show A − B = A + (−B) on the whiteboard.
Example: interview follow-up.
Swap operands and show opposite signs.
Example: B − A = −(A − B).
Huge magnitudes can still overflow int.
Example: suggest long long when needed.
Pro Tip: say “same shape, then cell minus cell” before writing the loops — and mention negatives up front.
Why this approach earns interview points.
Reuse the same structure; only the operator changes.
Macros or parameters for rows and columns scale cleanly.
O(m·n) is the expected answer.
2×2 and one row of 3×3 dry-run cleanly on a whiteboard.
Pro Tip: avoid unsigned when the result can be negative — mention that if the interviewer probes types.
Small habits that keep matrix-subtraction code clean in interviews.
Say both matrices are m × n before coding.
Write A - B, not a swapped expression by accident.
Use signed types; dry-run one cell that goes negative.
Mention A - B = A + (-B) if asked for theory.
Overwrite an operand only if you no longer need the original.
Pro Tip: the first-row walkthrough table is the fastest way to lock in negatives before typing the full nest.
Mistakes that commonly break matrix-subtraction solutions in C.
Subtracting differently sized matrices is undefined.
→ Require identical m and n.
Writing B - A when the prompt wants A - B.
→ Keep left and right factors in the stated order.
Negatives wrap around and look like huge positives.
→ Prefer signed int (or wider) when differences can be negative.
Adding a k loop is wrong for subtraction.
→ Stay with double nest and matching indices.
Extreme magnitudes can still overflow signed int.
→ Mention wider types for large inputs.
Most issues match matrix addition: wrong sizes or numeric range — plus signed results.
Subtraction needs identical dimensions, same as addition.
When B exceeds A in a cell, the difference is negative — that is correct.
Not commutative; reverse is the entrywise negation.
int overflowVery large magnitudes can overflow; consider wider integer types.
Avoid unsigned if negatives are possible.
Subtracting a matrix from itself yields the zero matrix — good sanity check.
Programs above embed matrices in source. Interactive versions would read values with scanf after checking dimensions.
| Sample | Result highlight |
|---|---|
| 3×3 demo | First row of A−B is 2 7 -5 |
| 2×2 demo | A−B = [[-3, -1], [1, 3]] |
Try these variations to lock in the pattern.
1 -5 7C = A − B with Cij = Aij − Bij; same shape required.A − B = A + (−B) entrywise.Quick Takeaway: match shapes, then for each cell compute A[i][j] - B[i][j] — same loops as addition, watch the order and the signs.
| Operation | Time | Extra space |
|---|---|---|
Subtract two m × n matrices | O(m · n) | O(1) besides result storage |
Matrix subtraction is the element-wise twin of addition: match shapes, nest two loops, and subtract corresponding entries — expecting negatives when B wins a cell. Master the 3×3 and 2×2 samples so you can generalize sizes on demand.
Practice both examples above, then continue to matrix transpose for flipping rows and columns.
Same shape, then C[i][j] = A[i][j] - B[i][j] for every cell — and remember order matters.
O(m·n) for the classic passint overflowImplement it the interview-friendly way.
Aij − Bij
DefinitionMust match
Constrainti, then j
CodeNegatives OK
ResultsO(m·n)
AnalysisMatrix 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.
Learn how to transpose a matrix by swapping rows and columns in C.
8 people found this page helpful