Here matrix division means element-wise division: C[i][j] = A[i][j] / B[i][j]. Both matrices need the same shape, and no cell in B may be zero.
Remember
A ÷ B (entrywise) is defined when shapes match and B has no zeros
[ 8 6 ] [ 2 3 ] [ 4.0 2.0 ]
[ 9 4 ] ÷ [ 3 2 ] = [ 3.0 2.0 ]
Rule: (A ÷ B)[i][j] = A[i][j] / B[i][j]
Note: this is not A × B⁻¹ from linear algebra.
Position
A
B
A / B
[0][0]
8
2
4.0
[0][1]
6
3
2.0
[1][0]
9
3
3.0
[1][1]
4
2
2.0
Approach
How to Divide Matrices in JavaScript
Four clear steps — same nested loops as addition, plus a zero guard.
Confirm both matrices have the same rows and columns.
Reject any zero in B before dividing.
Create a result matrix of that size.
Set result[i][j] = A[i][j] / B[i][j] for every cell.
Method
Idea
Time
Best for
Nested loops
Divide matching cells into a new 2D array
O(m × n)
Interviews, teaching
Safe divide
Validate shape + no zeros in B
O(m × n)
Safer production-style code
Pseudocode
Pseudocode
function DivideMatrices(A, B):
rows = rows of A
cols = cols of A
if rows != rows of B or cols != cols of B:
error "shapes must match"
C = new matrix[rows][cols]
for i from 0 to rows - 1:
for j from 0 to cols - 1:
if B[i][j] == 0:
error "division by zero"
C[i][j] = A[i][j] / B[i][j]
return C
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Rule
C[i][j] = A[i][j] / B[i][j]
Requirement
Same shape; B[i][j] ≠ 0
JS division
Always floating-point (5 / 2 === 2.5)
Display
n.toFixed(2) for two decimals
Not inverse
This is not A × B⁻¹
Classic check
[[8,6],[9,4]] ÷ [[2,3],[3,2]] = [[4,2],[3,2]]
Try it
Live Preview
Pick a sample pair to see matrices A, B, and A ÷ B (entrywise).
Tap a chip to run. All samples use nonzero divisors.
Result
A =
8 6
9 4
B =
2 3
3 2
A ÷ B =
4.00 2.00
3.00 2.00
Code
JavaScript Programs
Start with a clear nested-loop divider. Then add shape and zero checks for safer code.
Example 1 — Nested Loops
Divide two same-sized matrices cell by cell and print each value with two decimals.
JavaScript
function divideMatrices(a, b) {
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;
}
function printMatrix(m) {
for (let i = 0; i < m.length; i++) {
console.log(m[i].map((n) => n.toFixed(2)).join(" "));
}
}
const a = [[8, 6], [9, 4]];
const b = [[2, 3], [3, 2]];
printMatrix(divideMatrices(a, b));