- Diff
- 4 nested cells
Perform Matrix Subtraction in C#
What you’ll learn
- What matrix subtraction means: subtract elements at the same row and column.
- How to use
int[,]rectangular arrays,GetLength(0)/GetLength(1), and nested loops. - Two programs: a 3×3 reference demo and a 2×2 version with a dimension check, plus a live 2×2 preview.
Overview
Matrix subtraction mirrors addition: walk every cell with nested loops, store differences in a new matrix, and print rows with an inner loop plus WriteLine after each row. The only change in code is the - operator instead of +.
Two programs
3×3 full demo and 2×2 with size validation.
Live preview
Edit two 2×2 matrices and see A − B instantly.
Order matters
A − B and B − A differ — unlike addition.
Prerequisites
Nested for loops, 2D array syntax, and basic console output. Familiarity with matrix addition helps — the loop structure is identical.
using System;,staticmethods,Console.Write/WriteLine.- Know that
matrix[i, j]uses row indexithen column indexj.
What is matrix subtraction?
To subtract two matrices, subtract each pair of elements that share the same position: C[i,j] = A[i,j] - B[i,j].
Both matrices must have the same dimensions. A 3×3 minus another 3×3 works; mixing 2×3 with 3×2 does not. Results can be negative — that is expected when B[i,j] is larger than A[i,j].
Element-wise difference
If A and B are both m × n, the difference C is m × n with Cij = Aij − Bij for every row i and column j.
Top-left of the reference matrices: 5 − 3 = 2. Bottom-left: 3 − 8 = −5.
Quick examples
- Result
- Includes negatives
Think row by row: for each position, take the value from the first matrix and subtract the value from the second — same reading order as a spreadsheet.
Live preview
Edit two 2×2 matrices. The widget subtracts matching cells and shows A − B.
Algorithm
Goal: compute C = A - B for equal-sized matrices.
Read dimensions
rows = A.GetLength(0), cols = A.GetLength(1). Confirm B matches.
Allocate result
int[,] result = new int[rows, cols];
Nested loops
For each (i, j): result[i,j] = A[i,j] - B[i,j].
📜 Pseudocode
function subtractMatrices(A, B):
assert same rows and columns
rows ← row count of A
cols ← column count of A
C ← new matrix[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]
return C 3×3 matrix subtraction (reference)
Subtracts two fixed 3×3 matrices and prints both inputs plus Matrix1 - Matrix2. Several cells are negative when the second matrix has larger values.
using System;
class Program
{
static int[,] SubtractMatrices(int[,] mat1, int[,] mat2)
{
int rows = mat1.GetLength(0);
int cols = mat1.GetLength(1);
int[,] result = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
result[i, j] = mat1[i, j] - mat2[i, j];
}
}
return result;
}
static void DisplayMatrix(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
static void Main()
{
int[,] matrix1 = {
{ 5, 8, 2 },
{ 7, 4, 9 },
{ 3, 6, 1 }
};
int[,] matrix2 = {
{ 3, 1, 7 },
{ 6, 9, 2 },
{ 8, 5, 4 }
};
int[,] resultMatrix = SubtractMatrices(matrix1, matrix2);
Console.WriteLine("Matrix 1:");
DisplayMatrix(matrix1);
Console.WriteLine("\nMatrix 2:");
DisplayMatrix(matrix2);
Console.WriteLine("\nResultant Matrix (Matrix1 - Matrix2):");
DisplayMatrix(resultMatrix);
}
} Explanation
SubtractMatrices assumes both inputs share dimensions — fine for fixed literals in Main. The core line replaces + from addition with -. DisplayMatrix prints negative numbers normally with Console.Write.
result[i, j] = mat1[i, j] - mat2[i, j];Element-wise difference. Same indices on both sides — subtract the second matrix from the first.
2×2 subtraction with dimension check
Smaller matrices for beginners, plus SameDimensions so mismatched sizes fail fast with a clear message. Matches the live preview defaults.
using System;
class Program
{
static bool SameDimensions(int[,] a, int[,] b)
{
return a.GetLength(0) == b.GetLength(0)
&& a.GetLength(1) == b.GetLength(1);
}
static int[,] SubtractMatrices(int[,] mat1, int[,] mat2)
{
if (!SameDimensions(mat1, mat2))
{
throw new ArgumentException("Matrices must have the same dimensions.");
}
int rows = mat1.GetLength(0);
int cols = mat1.GetLength(1);
int[,] result = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
result[i, j] = mat1[i, j] - mat2[i, j];
}
}
return result;
}
static void DisplayMatrix(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
static void Main()
{
int[,] matrix1 = {
{ 7, 4 },
{ 6, 2 }
};
int[,] matrix2 = {
{ 3, 1 },
{ 6, 5 }
};
int[,] diff = SubtractMatrices(matrix1, matrix2);
Console.WriteLine("Matrix1 - Matrix2:");
DisplayMatrix(diff);
}
} Explanation
Matches the live preview: 7−3=4, 4−1=3, 6−6=0, 2−5=−3. In interviews, mention the dimension guard and that subtraction is not commutative.
Beyond the basics
In-place update. You can subtract B into A directly (A[i,j] -= B[i,j]) when you do not need to keep the original A.
double[,]. Same loops work for floating-point grids — useful when subtracting sensor readings or image channels.
Interview: state the size rule, note that order matters, draw a 2×2 example on paper, then write nested loops and a print helper.
❓ FAQ
🔄 Input / output examples
Replace literal matrices in Main, or read dimensions and values from the console in your own extension.
| A[i,j] | B[i,j] | Difference |
|---|---|---|
5 (top-left 3×3) | 3 | 2 |
2 (row 0, col 2) | 7 | -5 |
7 (2×2) | 3 | 4 |
2 (2×2) | 5 | -3 |
Edge cases and pitfalls
Most bugs come from dimension mismatches, swapped operand order, or confusing row/column indices.
Mismatched dimensions
Always verify row and column counts match before allocating result.
A - B vs B - A
Subtracting in the wrong order flips signs on every cell. State which matrix is minuend (first) and subtrahend (second).
[i, j] order
GetLength(0) is rows, GetLength(1) is columns — do not swap them in the loop bounds.
Negative results
Not an error — int handles negative differences. Only worry about overflow on extreme values.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Subtract m × n matrices | O(m × n) | O(m × n) for result |
DisplayMatrix | O(m × n) | O(1) |
Every cell is visited once — optimal for a straightforward difference.
Summary
- Rule:
C[i,j] = A[i,j] - B[i,j]for equal-sized matrices. - C#:
int[,], nestedforloops,GetLengthfor bounds — same as addition. - Remember: order matters;
A - Bis not the same asB - A.
Matrix subtraction is element-wise, just like addition — but order matters: A − B is generally not equal to B − A. Negative cells are normal when a value in the second matrix is larger.
5 people found this page helpful
