Perform Matrix Division in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Tables & division

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, and Number.prototype.toFixed for 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.

Later, you may hear “inverse matrices”

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.

4 ÷ 2 = 2
Where
Top-left of the 2×2 example
8 ÷ 4 = 2
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).

No typing needed—good for a quick check before you run the script in Node or DevTools.

Live result
Press “Show 2×2 division”.

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

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

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.

JavaScript
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);
Try it Yourself

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.

2

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

JavaScript
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);
}
Try it Yourself

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

Yes. Think of a matrix as a table of numbers. This program only does normal division in each box: top number ÷ bottom number in the same box. No special math course is required for that part.
It builds a new table. In every row and column, it takes the value from matrix A, divides it by the value from matrix B in the same position, and stores the answer. That is called element-wise (or entry-wise) division.
Often, no. In higher math, dividing by a matrix can mean multiplying by an inverse matrix. This tutorial does the simpler thing: divide matching cells. We say that clearly so you are not surprised later.
Division often gives decimals (for example 5 ÷ 2 = 2.5). JavaScript numbers are IEEE-754 doubles and keep those fractional answers. Plain integer-only rounding would hide the real quotient.
You cannot divide by zero. The first example only uses safe numbers. The second program checks before dividing and stops with a clear error message if it finds a zero in the bottom matrix.
It visits every cell once, so the time grows in proportion to the number of cells (rows times columns). Memory is small: you mostly store the two input tables and the result.

🔄 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:

Zero

Division by zero

Never divide if the bottom cell is zero. Example 2 shows one simple guard.

Shape

Mismatched tables

This method needs the same number of rows and columns in both matrices.

Words

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)

TaskTimeExtra memory
Divide two m × n tables this wayProportional 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).
Did you know?

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.

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