Skip to content
Master Python’s @ Operator: Matrix Multiplication Made Simple
Fundamentals 4 min read

Master Python’s @ Operator: Matrix Multiplication Made Simple

This article explains Python's @ operator for matrix multiplication, shows basic usage with NumPy, contrasts it with element‑wise *, demonstrates matrix‑vector multiplication, highlights common dimension‑mismatch errors, and provides a concise summary for efficient linear‑algebra calculations.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle

In Python, the @ symbol is the matrix multiplication operator introduced in Python 3.5; it performs matrix‑matrix and matrix‑vector products and is equivalent to NumPy’s np.dot() or np.matmul() functions.

Basic Usage

Example of multiplying two 2×2 matrices:

import numpy as np
# define two matrices
A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])
# matrix multiplication
C = A @ B
print(C)

Output:

[[19 22]
 [43 50]]
Matrix multiplication result
Matrix multiplication result

Difference from Element‑wise Multiplication

Using the * operator performs element‑wise (Hadamard) multiplication, not matrix multiplication:

D = A * B
print(D)

Output:

[[ 5 12]
 [21 32]]

Matrix‑Vector Multiplication

The @ operator also works between a matrix and a vector:

# define matrix and vector
A = np.array([[1, 2],
              [3, 4]])
v = np.array([5, 6])
# matrix‑vector multiplication
result = A @ v
print(result)

Output:

[17 39]
Matrix‑vector multiplication
Matrix‑vector multiplication

Common Errors and Tips

A dimension mismatch raises an error because the left matrix’s column count must equal the right matrix’s row count:

A = np.array([[1, 2],
               [3, 4]])
B = np.array([[5, 6]])   # shape (1,2)
C = A @ B   # ValueError: shapes (2,2) and (1,2) not aligned

Summary

The @ operator implements true matrix multiplication following linear‑algebra rules, suitable for both matrix‑matrix and matrix‑vector operations, and differs from the element‑wise * operator; using it with NumPy provides efficient linear‑algebra computation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonOperatormatrix multiplicationNumPylinear algebracoding
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.