0
0
NumPydata~5 mins

Matrix multiplication with @ operator in NumPy

Choose your learning style9 modes available
Introduction

Matrix multiplication helps combine data in rows and columns to find relationships. The @ operator makes this easy and clear.

When combining features and weights in machine learning models.
When transforming coordinates in graphics or physics.
When calculating total effects in economics or social sciences.
When working with multiple datasets that relate through matrix math.
Syntax
NumPy
result = matrix1 @ matrix2

The @ operator performs matrix multiplication, not element-wise multiplication.

Both matrices must have compatible shapes: columns in the first must equal rows in the second.

Examples
Multiply two 2x2 matrices using @.
NumPy
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
C = A @ B
Multiply a 1x3 matrix by a 3x1 matrix to get a 1x1 matrix.
NumPy
import numpy as np
X = np.array([[1, 2, 3]])
Y = np.array([[4], [5], [6]])
Z = X @ Y
Sample Program

This program multiplies two 2x2 matrices using the @ operator and prints the input matrices and the result.

NumPy
import numpy as np

# Define two matrices
matrix1 = np.array([[2, 3], [4, 5]])
matrix2 = np.array([[6, 7], [8, 9]])

# Multiply using @ operator
result = matrix1 @ matrix2

print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print("\nResult of matrix1 @ matrix2:")
print(result)
OutputSuccess
Important Notes

The @ operator was introduced in Python 3.5 for matrix multiplication.

Using @ is clearer and less error-prone than using np.dot() or np.matmul().

Summary

The @ operator multiplies matrices when their shapes match.

It is simple and readable for matrix math in numpy.

Use it to combine data in rows and columns easily.