Perform Matrix Division in Python

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Lists & division

What you’ll learn

  • Simple idea: divide two same-sized tables by dividing matching cells (top รท bottom in each position).
  • Why we use decimal output and why division by zero must be checked first.
  • Two Python examples: a basic 2x2 version and a safer version that stops when a divisor is zero.

Overview

This lesson uses element-wise division. For each index pair (i, j), compute A[i][j] / B[i][j]. The two matrices must have identical shape.

Two examples

A direct 2x2 demo and a safe zero-checking version.

Live preview

See the same sample numbers computed in-browser.

Clear terminology

We distinguish this beginner method from inverse-matrix division.

Before you start

Just basic Python lists, loops, and division.

  • Know how matrices can be stored as nested lists, for example [[4.0, 8.0], [2.0, 6.0]].
  • Remember that division by zero is invalid and should be handled.

In plain English

If matrix A and matrix B have the same rows and columns, then each result cell is:

result[i][j] = A[i][j] / B[i][j]

Each position is independent. You never combine values from different rows/columns. Just divide matching positions.

About the word "division"

This tutorial is about entry-wise division. Advanced linear algebra may define matrix division differently using inverses.

Pocket calculator picture

Imagine pressing one calculator operation per cell.

4 / 2 = 2
Where
Top-left cell of the sample
8 / 4 = 2
Where
Top-right cell of the sample

Following this per-cell rule, every output in our sample becomes 2.00.

Live preview

Runs the same 2x2 sample as code example 1. Click once to show A, B, and A / B (cell by cell).

No typing needed - ideal for quick revision.

Live result
Press "Show 2x2 division".

Algorithm (simple steps)

Goal: build a result matrix by dividing matching cells in two equal-sized matrices.

Validate shape

Both matrices must have the same rows and columns.

Nested loops

Loop over each index pair (i, j) to process every cell once.

Guard and divide

If B[i][j] == 0, stop with an error. Otherwise set R[i][j] = A[i][j] / B[i][j].

📜 Pseudocode

Pseudocode
function divide_elementwise(A, B):
    ensure A and B have same shape
    create empty Result
    for each row i:
        for each column j:
            if B[i][j] == 0:
                raise error
            Result[i][j] <- A[i][j] / B[i][j]
    return Result
1

2x2 element-wise division (main example)

Simple and direct: two nested loops, decimal formatting, and safe sample values (no zero in matrix B).

python
ROWS = 2
COLS = 2

def print_matrix(matrix: list[list[float]]) -> None:
    for i in range(ROWS):
        row_text = "\t".join(f"{matrix[i][j]:.2f}" for j in range(COLS))
        print(row_text)

def divide_matrices(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
    out = [[0.0 for _ in range(COLS)] for _ in range(ROWS)]
    for i in range(ROWS):
        for j in range(COLS):
            out[i][j] = a[i][j] / b[i][j]
    return out

def main() -> None:
    matrix_a = [
        [4.0, 8.0],
        [2.0, 6.0]
    ]
    matrix_b = [
        [2.0, 4.0],
        [1.0, 3.0]
    ]
    result = divide_matrices(matrix_a, matrix_b)

    print("Result of matrix division:")
    print_matrix(result)

if __name__ == "__main__":
    main()

What each part does

The core line is out[i][j] = a[i][j] / b[i][j]. The print helper formats to two decimals.

for i in range(ROWS): for j in range(COLS):

Traversal: visits every matrix cell exactly once.

f"{matrix[i][j]:.2f}"

Formatting: keeps output neat and consistent for learners.

2

Same idea, but stop if any divisor is zero

This version checks matrix B first and raises a clear error before dividing.

python
ROWS = 2
COLS = 2

def has_zero(matrix: list[list[float]]) -> bool:
    for i in range(ROWS):
        for j in range(COLS):
            if matrix[i][j] == 0.0:
                return True
    return False

def divide_matrices(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
    out = [[0.0 for _ in range(COLS)] for _ in range(ROWS)]
    for i in range(ROWS):
        for j in range(COLS):
            out[i][j] = a[i][j] / b[i][j]
    return out

def print_matrix(title: str, matrix: list[list[float]]) -> None:
    print(title)
    for i in range(ROWS):
        print("\t".join(f"{matrix[i][j]:.2f}" for j in range(COLS)))

def main() -> None:
    a = [[4.0, 8.0], [2.0, 6.0]]
    b = [[2.0, 4.0], [1.0, 3.0]]

    if has_zero(b):
        raise ValueError("Cannot divide: matrix B contains a zero.")

    r = divide_matrices(a, b)

    print_matrix("A", a)
    print()
    print_matrix("B", b)
    print()
    print_matrix("A / B (cell by cell)", r)

if __name__ == "__main__":
    main()

Why this matters

Early validation avoids runtime crashes and communicates errors clearly.

Going further (optional)

Bigger matrices. Generalize ROWS and COLS, then validate shape before processing.

Advanced math path. True matrix division in linear algebra usually involves inverses and multiplication, which is a separate topic.

❓ FAQ

No. Here a matrix is treated as a table of numbers, and each result cell is top divided by bottom at the same position.
It creates a result matrix where result[i][j] = A[i][j] / B[i][j], so it is element-wise (entry-wise) division.
Usually not. In higher math, matrix division often means multiplying by an inverse matrix. This tutorial uses the simpler cell-by-cell division.
Because division often gives decimals, like 5 / 2 = 2.5. Float formatting keeps those values visible.
Division by zero is not allowed. The safe example checks B first and stops with a clear error message.
For an m x n matrix, every cell is visited once, so time is O(m*n). Extra space is mainly the output matrix.

🔄 Input and output

These examples use hardcoded matrices for clarity. For user input, parse rows into lists, verify same shape, verify no zero in matrix B, then compute the result.

Watch out for

Three practical reminders for beginners:

Zero

Division by zero

Always check matrix B values before dividing.

Shape

Mismatched matrices

Entry-wise operations need same row and column counts.

Meaning

Term confusion

Say “element-wise division” when discussing this method in interviews.

⏱️ Time and space (big picture)

TaskTimeExtra memory
Divide two m x n matrices entry-wiseO(m*n)Mainly output matrix

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

Summary

  • Idea: divide matching cells in same-sized matrices.
  • Code: nested loops with zero checks for safety.
  • Note: this is different from inverse-based matrix division in advanced math.
Did you know?

This page uses cell-by-cell division: each number is divided only by the number in the same row and column. In advanced math, matrix “division” can mean multiplying by an inverse matrix, which is a different 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