How to multiply matrices with NumPy

Matrix multiplication combines rows and columns into weighted totals, which makes it a core operation in coordinate transforms, linear models, and equation systems. NumPy performs this calculation directly on regular arrays without manual nested loops.

For two-dimensional arrays, the left matrix shape (n, k) and right matrix shape (k, m) produce a result shaped (n, m). The shared inner dimension must match because each left row is paired with every right column.

The @ operator is the clearest form for two-dimensional matrix products and has the same semantics as np.matmul(). Keep * and np.multiply() for element-wise multiplication, and use ordinary ndarray values because the older numpy.matrix class is no longer recommended.

Steps to multiply matrices with NumPy:

  1. Create matrix-multiply.py with NumPy and two compatible operand arrays.
    matrix-multiply.py
    import numpy as np
     
    left = np.array(
        [
            [2, 1, 3],
            [0, 4, 5],
        ]
    )
    right = np.array(
        [
            [1, 2],
            [3, 0],
            [4, 1],
        ]
    )

    The left matrix has three columns and the right matrix has three rows, so their shared inner dimension is compatible.

  2. Insert an inner-dimension check below the right array definition.
    if left.shape[1] != right.shape[0]:
        message = (
            f"left shape {left.shape} is incompatible "
            f"with right shape {right.shape}"
        )
        raise ValueError(message)

    This check reports the actual shapes before @ raises a lower-level dimension error, which is helpful when operands come from files or earlier transforms.

  3. Append the matrix product and expected-result checks to matrix-multiply.py.
    product = left @ right
    expected = np.array(
        [
            [17, 7],
            [32, 5],
        ]
    )
     
    np.testing.assert_array_equal(product, expected)
    assert product.shape == (2, 2)
     
    print("product:")
    print(product)
    print("shape:", product.shape)
    print("matches expected:", np.array_equal(product, expected))
  4. Run the completed matrix multiplication script.
    $ python3 matrix-multiply.py
    product:
    [[17  7]
     [32  5]]
    shape: (2, 2)
    matches expected: True

    The command exits with an assertion error if either the values or the (2, 2) result shape differs from the expected matrix.