Perform Matrix Subtraction in JavaScript
What you’ll learn
- The element-wise rule
Cij = Aij − Bijfor matrices of the same size. - A complete 3×3 program (including negative differences), a compact 2×2 variant, a live preview, and Try it (
target="_blank"). - How subtraction relates to addition (
A − B = A + (−B)) and common interview follow-ups.
Overview
Subtracting matrices works like subtracting numbers in a table: the top-left result uses the top-left of A minus the top-left of B, and so on for every cell.
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 exceeds A in a cell.
Prerequisites
Same as matrix addition: nested loops and arrays of arrays.
console.logand row-major indexingmat[i][j]; literals like[[1, 2], [3, 4]].- JavaScript numbers can be negative; subtraction produces negatives naturally.
What is matrix subtraction?
For matrices A and B with the same shape, C = A − B is defined by Cij = Aij − Bij for every row i and column j.
Equivalently, subtracting B is adding (−B) entrywise.
Live preview
Uses the same 3×3 inputs as example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.
Algorithm
Goal: compute C[i][j] = A[i][j] - B[i][j] for all cells.
Same shape
A and B must share row and column counts.
Subtract per cell
Nested loops over i and j; assign the difference to result[i][j].
Optional helper to print each row with console.log.
📜 Pseudocode
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]Subtract two 3×3 matrices (program with explanation)
subtractMatrices computes matrix1 − matrix2. Values match the reference walkthrough (differences can be negative).
const N = 3;
function subtractMatrices(mat1, mat2) {
const result = [];
for (let i = 0; i < N; i++) {
result[i] = [];
for (let j = 0; j < N; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
return result;
}
function displayMatrix(matrix) {
for (let i = 0; i < N; i++) {
let line = "";
for (let j = 0; j < N; j++) {
line += matrix[i][j] + "\t";
}
console.log(line);
}
}
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("");
console.log("Matrix 2:");
displayMatrix(matrix2);
console.log("");
console.log("Resultant Matrix (Matrix1 - Matrix2):");
displayMatrix(resultMatrix);Explanation
Each result[i][j] is one subtraction. Tab spacing keeps columns readable in the console.
Subtract two 2×2 matrices
Same pattern with ROWS / COLS; useful when an interviewer asks for a smaller trace-by-hand example.
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);Explanation
Here 1 - 4 = -3 and 4 - 1 = 3 show negatives and positives in one small grid.
Notes
In place. You could write differences back into one array only if you no longer need the original operand stored there.
Unsigned bit tricks. Avoid treating differences as unsigned 32-bit values (>>> patterns): negatives become huge positives and hide bugs.
❓ FAQ
🔄 Input / output
Programs above embed matrices in source. Interactive versions would read values into nested arrays (for example with prompt or readline) after checking dimensions.
Edge cases
Most issues match matrix addition: wrong sizes or numeric range.
Mismatched matrices
Subtraction needs identical dimensions, same as addition.
Numeric overflow
Very large magnitudes can exceed safe integer range when subtracting; consider BigInt or floating-point.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Subtract two m × n matrices | O(m · n) | O(1) besides result storage |
Summary
- Definition:
C = A − BwithCij = Aij − Bij; same shape required. - Code: nested loops; each cell is one subtraction.
- Relation:
A − B = A + (−B)entrywise.
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
