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.
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:
<code>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)</code>Output:
<code>[[19 22]
[43 50]]</code>Difference from Element‑wise Multiplication
Using the
*operator performs element‑wise (Hadamard) multiplication, not matrix multiplication:
<code>D = A * B
print(D)</code>Output:
<code>[[ 5 12]
[21 32]]</code>Matrix‑Vector Multiplication
The
@operator also works between a matrix and a vector:
<code># define matrix and vector
A = np.array([[1, 2],
[3, 4]])
v = np.array([5, 6])
# matrix‑vector multiplication
result = A @ v
print(result)</code>Output:
<code>[17 39]</code>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:
<code>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</code>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.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.