- Where
- Top-left of the 2×2 example
Perform Matrix Division in JavaScript
What you’ll learn
- In plain English: how to divide two same-sized tables by dividing matching cells (like stacking two spreadsheets and dividing top ÷ bottom in each cell).
- Why programs here use JavaScript numbers for quotients, and why divide-by-zero must be handled.
- Two short examples: a straight 2×2 demo and a version that refuses to divide when the bottom cell is zero, plus Try it (
target="_blank").
Overview
Picture two grids with the same number of rows and columns. For each box, you divide the number on top by the number directly below it. That is all this lesson implements in JavaScript. We call it element-wise division.
Two programs
A tiny 2×2 example with decimals, plus a safe version that checks for zeros.
Live preview
See the same numbers as example 1 computed in your browser.
Honest wording
We separate this simple idea from harder “inverse matrix” math so beginners do not get lost.
Before you start
You only need basic arithmetic (division), plus the idea of a loop that visits each row and column.
console.log, nested arrays, andNumber.prototype.toFixedfor tidy columns.- You know that dividing by zero is not allowed.
In plain English
A matrix here is just a rectangle of numbers. If matrix A and matrix B have the same shape, the result in row i, column j is:
answer[i][j] = A[i][j] ÷ B[i][j]
Example: top-left is 4 ÷ 2 = 2, next cell is 8 ÷ 4 = 2, and so on. Each spot is independent: you never mix numbers from different boxes.
In advanced courses, “dividing by a matrix” can mean something deeper (multiply by an inverse). This tutorial does not do that. It only divides number-by-number in matching cells. Both ideas are real; they are not the same program.
Pocket calculator picture
Treat each pair like pressing “A cell ÷ B cell” on a calculator.
- Where
- Top-right of the same example
Every other cell in the sample works the same way. That is why the final table is all 2.00 in this particular exercise.
Live preview
These are the same starting numbers as code example 1. Press the button to see A, B, and A ÷ B (cell by cell).
Algorithm (simple steps)
Goal: fill a new table so each cell equals the top number divided by the bottom number in that cell.
Line up the grids
Both tables must have the same height and width. If they do not, this simple method does not apply.
Walk each row and column
Use one loop for rows and one loop for columns (nested loops). Visit every cell once.
Divide carefully
Before dividing, make sure the bottom value is not zero. Then store a[i][j] / b[i][j] in the answer table.
📜 Pseudocode
function divide_elementwise(A, B, Result, rows, cols):
for i from 0 to rows - 1:
for j from 0 to cols - 1:
if B[i][j] is zero:
stop with an error (cannot divide)
Result[i][j] ← A[i][j] / B[i][j]2×2 element-wise division (main example)
This matches the classic walkthrough: floating-point values, two nested loops, and a print helper. The sample numbers are chosen so every bottom cell is nonzero, so division is always safe.
const ROWS = 2;
const COLS = 2;
function printMatrix(m) {
for (let i = 0; i < ROWS; i++) {
let line = "";
for (let j = 0; j < COLS; j++) {
line += m[i][j].toFixed(2) + "\t";
}
console.log(line);
}
}
function divideMatrices(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;
}
const matrixA = [
[4.0, 8.0],
[2.0, 6.0],
];
const matrixB = [
[2.0, 4.0],
[1.0, 3.0],
];
const result = divideMatrices(matrixA, matrixB);
console.log("Result of matrix division:");
printMatrix(result);What each part does
divideMatrices is the heart: one division per cell. printMatrix only prints; it does not change the math.
out[i][j] = a[i][j] / b[i][j];Same address, two tables. i picks the row, j picks the column. Always the same (i, j) on both sides.
toFixed(2) + "\t"Two decimal places so the output looks tidy. The tab adds space between columns.
Same idea, but stop if a divisor is zero
Real programs should not silently divide by zero. This version checks B first. If it finds a zero, it prints a short message and exits (here using process.exit(1) in Node; in the browser you might return early instead).
const ROWS = 2;
const COLS = 2;
function bHasZero(b) {
for (let i = 0; i < ROWS; i++) {
for (let j = 0; j < COLS; j++) {
if (b[i][j] === 0) {
return true;
}
}
}
return false;
}
function divideMatrices(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++) {
let line = "";
for (let j = 0; j < COLS; j++) {
line += m[i][j].toFixed(2) + "\t";
}
console.log(line);
}
}
const a = [
[4.0, 8.0],
[2.0, 6.0],
];
const b = [
[2.0, 4.0],
[1.0, 3.0],
];
if (bHasZero(b)) {
console.log("Cannot divide: matrix B contains a zero.");
if (typeof process !== "undefined") process.exit(1);
} else {
const r = divideMatrices(a, b);
printMatrix("A", a);
console.log("");
printMatrix("B", b);
console.log("");
printMatrix("A / B (cell by cell)", r);
}Why this matters
Comparing floats with === 0 is not perfect in serious floating-point work, but it is easy to read for a first course. For money or science-grade code, people use tolerances or separate validation rules.
Going further (optional)
Bigger tables. Change ROWS and COLS, or derive sizes from a.length and a[0].length, as long as both matrices still match.
Need true matrix division in the math-club sense? That usually means learning matrix inverses and matrix multiplication. Treat that as a separate project; this page stays with the easy cell-by-cell idea.
❓ FAQ
🔄 Input and output
These samples put numbers directly in the code. To try your own values, change the arrays (or read values with prompt in the browser or readline in Node). Always keep A and B the same size, and keep every B cell nonzero unless you add error handling.
Watch out for
Three practical reminders while you are learning:
Division by zero
Never divide if the bottom cell is zero. Example 2 shows one simple guard.
Mismatched tables
This method needs the same number of rows and columns in both matrices.
Name confusion
Say “element-wise division” if a teacher asks, so they know you mean cell-by-cell, not inverse matrices.
⏱️ Time and space (big picture)
| Task | Time | Extra memory |
|---|---|---|
Divide two m × n tables this way | Proportional to m · n (each cell once) | Small: mostly the output table |
You do not need to memorize symbols here. The idea is: bigger grids take longer because there are more cells.
Summary
- Idea: divide each top cell by the bottom cell in the same position. Same shape for both tables.
- Code: two nested loops and floating-point division; guard against zero if inputs vary.
- Not the same as: multiplying by an inverse matrix (advanced topic).
This page uses cell-by-cell division: each number is only divided by the number in the same row and column. That is a simple idea. University math also talks about A × B−1 for “dividing” matrices—that is a different, harder topic.
8 people found this page helpful
