Perform Matrix Subtraction in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2D lists

What You’ll Learn

Element-wise matrix subtraction subtracts matching cells: C[i][j] = A[i][j] - B[i][j], only when shapes match. This tutorial covers the rule, nested loops, negatives, a live preview, worked JavaScript examples, edge cases, and complexity.

Definition

Entrywise −

Each output cell is A minus B at the same index.

Same Shape

m × n both

Subtraction is defined only when dimensions match.

Order Matters

Not A = B

A − B differs from B − A (they are negatives).

Negatives OK

Signed cells

Result entries can be negative — that is normal.

Live Preview

Show 3×3

Run the classic 3×3 sample difference in the browser.

Like Addition

A + (−B)

Same nested-loop pattern as addition, different operator.

Introduction

Matrix subtraction on this page means element-wise difference: if A and B are both m × n, then C[i][j] = A[i][j] - B[i][j] for every cell.

Shapes must match. Order matters: B - A = -(A - B). You can also think of it as A + (-B) entrywise.

Why it matters?

It reuses the same nested-loop pattern as addition while highlighting negatives and non-commutativity — great interview follow-ups.

Key Highlights

Same Positions

Top-left subtracts top-left — never mix cells.

Negatives Fine

Signed results are expected when A < B.

Two Nested Loops

Visit each cell once and subtract.

Not Multiplication

Different rules from row–column products.

In short: if shapes match, set C[i][j] = A[i][j] - B[i][j] with nested loops; expect negatives.

📝 Problem & Approach

Given two equal-sized matrices A and B, build C where each cell is the difference of corresponding cells.

JavaScript
# [[5, 8], [7, 4]] - [[3, 1], [6, 9]] = [[2, 7], [1, -5]]
# Same shape required; order matters (A - B ≠ B - A)

Inputs & Outputs

ItemTypeDescription
A, B2D arraysTwo matrices with the same shape.
Return / printmatrix / textResult matrix with entrywise differences (may include negatives).

Minimal workflow

Pseudocode
function subtractMatrices(A, B):
    for each row i:
        for each column j:
            C[i][j] <- A[i][j] - B[i][j]
    return C

Method comparison

MethodIdeaNotes
Nested loopsC[i][j] = A[i][j] - B[i][j]Interview default — clear indexing
Via negationA + (-B) entrywiseSame result; useful math intuition
Matrix productRow–column dotsDifferent operation — not this page

⚡ Quick Reference

GoalPattern
Subtract cellout[i][j] = a[i][j] - b[i][j]
Traversefor (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++)
Build rowsresult[i][j] = ... or push row arrays
Fresh gridArray.from({ length: rows }, () => Array(cols).fill(0))
Shape checkSame rows and uniform column lengths
Order reminderB - A = -(A - B)

📋 Subtraction vs Addition vs Multiplication

Same nested loops for +/− — different rules for products.

Subtraction
A[i][j] - B[i][j]

This page — same shape required

Addition
A[i][j] + B[i][j]

Same traversal; different operator

Multiplication
sum A[i][k]*B[k][j]

Different shape rule and formula

Interview tip
mention order

Say A − B is not B − A

Context

When This Problem Shows Up

Reach for element-wise subtraction when grids differ cell by cell.

  1. Interview warm-ups

    Same loops as addition, plus negatives and order.

  2. After multiplication

    Natural return to entrywise ops in this chain.

  3. Difference grids

    Compare two tables cell by cell (deltas, errors).

  4. Teaching signed ints

    Practice printing and reasoning about negatives.

  5. Not for products

    Clarify when the interviewer wants true matrix multiply.

Key benefit: one short 2D problem that locks in indexing, same-shape checks, and non-commutative order.

🔮 Live Preview

Uses the same 3×3 sample as Example 1. Click to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.

Matches the first JavaScript code example below.

Live result
Press “Show 3x3 difference”.

Examples Gallery

Three complete JavaScript programs — classic 3×3 difference, easy 2×2 check, and a shape-safe general subtractor. Click View Output to reveal sample console results.

📚 Getting Started

Two nested loops and one subtraction per cell — negatives included.

Example 1 — Subtract Two 3×3 Matrices

subtractMatrices computes matrix1 − matrix2. Some output values are negative, which is expected.

JavaScript
function subtractMatrices(mat1, mat2) {
  const result = [];
  for (let i = 0; i < 3; i++) {
    result[i] = [];
    for (let j = 0; j < 3; j++) {
      result[i][j] = mat1[i][j] - mat2[i][j];
    }
  }
  return result;
}

function displayMatrix(matrix) {
  for (let i = 0; i < matrix.length; i++) {
    console.log(matrix[i].join("\t"));
  }
}

const matrix1 = [
  [5, 8, 2],
  [7, 4, 9],
  [3, 6, 1],
];
const matrix2 = [
  [3, 1, 7],
  [6, 9, 2],
  [8, 5, 4],
];

const resultMatrix = subtractMatrices(matrix1, matrix2);

console.log("Matrix 1:");
displayMatrix(matrix1);
console.log("\nMatrix 2:");
displayMatrix(matrix2);
console.log("\nResultant Matrix (Matrix1 - Matrix2):");
displayMatrix(resultMatrix);

How It Works

Every result cell performs exactly one subtraction from matching positions. Top-right is 2 - 7 = -5 — negatives are correct, not bugs.

⚡ Easy Manual Check

Smaller matrix, same logic — good for quick interview dry-run.

Example 2 — Subtract Two 2×2 Matrices

Compact example showing both negative and positive result cells.

JavaScript
const ROWS = 2;
const COLS = 2;

function subtractMatrices(a, b) {
  const out = [];
  for (let i = 0; i < ROWS; i++) {
    out[i] = [];
    for (let j = 0; j < COLS; j++) {
      out[i][j] = a[i][j] - b[i][j];
    }
  }
  return out;
}

function printMatrix(title, m) {
  console.log(title);
  for (let i = 0; i < ROWS; i++) {
    console.log(m[i].join(" "));
  }
}

const a = [[1, 2], [3, 4]];
const b = [[4, 3], [2, 1]];
const c = subtractMatrices(a, b);

printMatrix("A", a);
console.log();
printMatrix("B", b);
console.log();
printMatrix("A - B", c);

How It Works

Top-left is 1 - 4 = -3; bottom-right is 4 - 1 = 3. Matching the printed A − B confirms the cell-by-cell rule.

⚙️ Shape Validation

Generalize beyond fixed sizes with a same-shape guard.

Example 3 — Shape-Safe Element-Wise Subtraction

Checks matching shapes, then subtracts with nested loops.

JavaScript
function sameShape(a, b) {
  if (!a.length || !b.length) {
    return false;
  }
  if (a.length !== b.length) {
    return false;
  }
  const cols = a[0].length;
  if (cols === 0) {
    return false;
  }
  const all = a.concat(b);
  for (const row of all) {
    if (row.length !== cols) {
      return false;
    }
  }
  return true;
}

function subtractSafe(a, b) {
  if (!sameShape(a, b)) {
    return null;
  }
  const rows = a.length;
  const cols = a[0].length;
  const result = [];
  for (let i = 0; i < rows; i++) {
    result[i] = [];
    for (let j = 0; j < cols; j++) {
      result[i][j] = a[i][j] - b[i][j];
    }
  }
  return result;
}

const ok = subtractSafe([[5, 8, 2], [7, 4, 9], [3, 6, 1]], [[3, 1, 7], [6, 9, 2], [8, 5, 4]]);
const bad = subtractSafe([[1, 2], [3, 4]], [[5, 6, 7]]);
console.log(JSON.stringify(ok));
console.log(bad);

How It Works

Shape checks catch bad input before any subtraction. Returning null (or throwing) is clearer than a runtime index error mid-loop.

🧠 How the Algorithm Builds C

1

Validate shape

Both matrices must have the same rows and columns.

Shape
2

Nested loops

For each i and j, assign C[i][j] = A[i][j] - B[i][j].

Loops
3

Allow negatives

If A is smaller than B at a cell, the result is negative.

Signed
=

Difference matrix ready

C has the same shape as A and B.

🔎 Worked Walkthrough — First Row of 3×3

Trace the first row for Example 1: [5, 8, 2] - [3, 1, 7].

(i, j)ABC
(0, 0)532
(0, 1)817
(0, 2)27-5

First row of the result is [2, 7, -5] — matching Example 1 output.

Use Cases

Where element-wise matrix subtraction shows up beyond the interview prompt.

1. Interview Warm-Ups

2D indexing plus signed results.

Example: write subtractMatrices(A, B).

2. After Multiplication

Return to entrywise ops after products.

Example: swap * loops for −.

3. Difference Tables

Compare two grids cell by cell.

Example: forecast − actual.

4. Negation Practice

Relate A − B to A + (−B).

Example: flip B then add.

5. Order Awareness

Show B − A is the negative of A − B.

Example: dry-run both orders.

6. Precursor to Transpose

Next page flips rows and columns.

Example: continue the matrix chain.

Pro Tip: open with “element-wise subtraction, same shape, A − B not B − A” before writing loops.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Simple Formula

    One cell rule: C[i][j] = A[i][j] - B[i][j].

  2. 2. Reuses Addition Pattern

    Same nested loops you already know from matrix addition.

  3. 3. Forces Order Thinking

    Non-commutativity is a natural interview follow-up.

  4. 4. Easy Dry-Run

    2×2 samples verify understanding in seconds.

Pro Tip: lead with loops and same-shape; mention Library A - B only as a production aside.

Usage Tips

Small habits that keep matrix-subtraction solutions interview-ready.

  1. 1. Say Element-Wise First

    Avoid confusion with matrix multiplication.

  2. 2. Check Shapes Before Looping

    Reject mismatched dimensions early.

  3. 3. Expect Negatives

    Do not treat negative cells as errors.

  4. 4. Build Fresh Row Lists

    Avoid [[0]*cols]*rows shared references.

  5. 5. State O(m·n)

    One subtraction (and visit) per cell.

Pro Tip: dry-run 2 - 7 = -5 aloud on the 3×3 sample — if that matches, your indexing is correct.

Common Pitfalls

Mistakes that commonly break matrix-subtraction solutions.

  1. 1. Mismatched Shapes

    Subtracting matrices with different sizes.

    → Validate rows and columns first.

  2. 2. Wrong Operand Order

    Computing B − A when A − B was asked.

    → Subtract in the requested order only.

  3. 3. Confusing With Multiplication

    Using triple loops or dot products by mistake.

    → Say “element-wise” and stick to matching cells.

  4. 4. Treating Negatives as Errors

    Assuming all result cells must be positive.

    → Negatives are valid when A < B at a cell.

  5. 5. Shared Row Initialization

    [[0]*cols]*rows shares row lists.

    → Build each row separately.

Edge Cases

Common mistakes to avoid — plus a few more.

Shape

Mismatched matrices

Subtraction is valid only when dimensions are identical.

Order

Wrong operand order

A − B and B − A are different results.

Signed

Negative cells

Expected when A[i][j] < B[i][j] — not an error.

Ragged

Uneven rows

Validate every row length equals cols.

Zeros

Zero result cells

Equal matching entries yield 0 — still valid.

1×1

Single cell

Still uses the same formula — one subtraction.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Entrywise. (A − B)ij = Aij − Bij.
  • Not commutative. A − B is generally not equal to B − A.
  • Via addition. A − B = A + (−B) entrywise.
  • Anticommutative. B − A = −(A − B).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run 2×2

  • Reproduce Example 2 by hand
  • Expect [[-3, -1], [1, 3]]

2. Trace a negative cell

  • Compute 2 − 7 from Example 1
  • Confirm -5 in the output

3. Reverse order

  • Compute B − A for Example 2
  • Verify it is the negative of A − B

4. Shape rejection

  • 2×2 − 2×3 → null or throw
  • Same checks as addition

Notes

  • Definition: C[i][j] = A[i][j] - B[i][j] for same-shaped matrices.
  • Code: two nested loops and one subtraction per cell.
  • Relation: A - B = A + (-B) entrywise.
  • Complexity is O(m*n) — one visit (and subtraction) per cell. In-place overwrite is optional if originals are not needed.

Quick Takeaway: same shape, then C[i][j] = A[i][j] - B[i][j] with nested loops; order matters and negatives are fine.

⏱️ Time and Space Complexity

OperationTimeExtra space
Subtract two m × n matricesO(m*n)O(1) besides result matrix
Shape validationO(m) row checksO(1)
In-place overwriteO(m*n)O(1) if originals unused

As matrix size grows, runtime grows proportionally to the number of cells.

Wrap Up

🎉 Conclusion

Element-wise matrix subtraction subtracts matching cells when shapes match. Use nested loops, expect negatives, and remember that A − B is not the same as B − A.

Practice the three examples above, then continue to matrix transpose for the next 2D operation.

Same shape first, then C[i][j] = A[i][j] - B[i][j]; order matters.

💡 Best Practices

✅ Do

  • Say “element-wise subtraction” first
  • Validate shape before looping
  • Accept negative result cells
  • Mention A − B ≠ B − A
  • State O(m*n) complexity

❌ Don’t

  • Subtract mismatched shapes
  • Confuse this with matrix products
  • Treat negatives as bugs
  • Flip operand order silently
  • Use shared-row list init

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix subtraction

Subtract matrices the interview-friendly way.

5
Core concepts
= 02

Shape

Same m × n

Constraint
! 03

Order

A−B ≠ B−A

Property
04

Signed

Negatives OK

Output
O 05

Cost

O(m·n)

Analysis

❓ Frequently Asked Questions

Subtraction works cell by cell like addition: same position in A minus same position in B. Matrix multiplication combines rows of A with columns of B and is a different operation entirely.
Yes. Each entry of A − B needs a matching entry in B, so both must be m×n for the same m and n.
Usually no. Subtraction is not commutative: B − A is the negative of A − B entrywise.
Yes. If A[i][j] < B[i][j], the difference at that cell is negative. JavaScript numbers represent negatives naturally.
Subtracting two large integers can exceed Number.MAX_SAFE_INTEGER in edge cases. Use BigInt matrices if inputs can be huge.
Each of the m·n entries is computed once: O(m·n) time and O(1) extra space besides the output matrix.
A − B is the same as A + (−B) entrywise — flip signs in B, then add.
Libraries can subtract matrices element-wise in bulk. Interviews usually want nested loops first so you show indexing clearly.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Did you Know? 🔊

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.

Continue to Matrix Transpose

Learn how to flip rows and columns to build the transpose of a matrix.

Matrix transpose tutorial →

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.

8 people found this page helpful