Perform Matrix Subtraction in C#

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
2D arrays

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;, static methods, Console.Write / WriteLine.
  • Know that matrix[i, j] uses row index i then column index j.

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].

C[i,j] A[i,j]−B[i,j]
Size must match
Order A−B ≠ B−A

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.

Sample cell

Top-left of the reference matrices: 5 − 3 = 2. Bottom-left: 3 − 8 = −5.

Quick examples

2×2 Beginner
Diff
4 nested cells
3×3 Reference
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.

Matrix A

Matrix B

Default difference: [[4,3],[0,-3]].

Live result
Press “Subtract matrices” to compute 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

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
1

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.

c#
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×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.

c#
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

Subtract corresponding elements from two matrices of the same size. Result[i,j] = A[i,j] - B[i,j].
No. Both matrices must have the same number of rows and columns.
No. A - B is not the same as B - A unless the matrices are equal.
Top-left cell: 5 - 3 = 2. Several cells become negative, e.g. 2 - 7 = -5 in row 0, column 2.
For int[,] matrix: rows = matrix.GetLength(0), columns = matrix.GetLength(1).
Nested for loops over row index i and column index j, visiting every cell once — same pattern as matrix addition.
Subtraction works on matching cells. Multiplication combines rows and columns with dot products — a different operation entirely.

🔄 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)32
2 (row 0, col 2)7-5
7 (2×2)34
2 (2×2)5-3

Edge cases and pitfalls

Most bugs come from dimension mismatches, swapped operand order, or confusing row/column indices.

Size

Mismatched dimensions

Always verify row and column counts match before allocating result.

Order

A - B vs B - A

Subtracting in the wrong order flips signs on every cell. State which matrix is minuend (first) and subtrahend (second).

Index

[i, j] order

GetLength(0) is rows, GetLength(1) is columns — do not swap them in the loop bounds.

Negatives

Negative results

Not an error — int handles negative differences. Only worry about overflow on extreme values.

⏱️ Time and space complexity

OperationTimeExtra space
Subtract m × n matricesO(m × n)O(m × n) for result
DisplayMatrixO(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[,], nested for loops, GetLength for bounds — same as addition.
  • Remember: order matters; A - B is not the same as B - A.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful