dot() and matmul() (NumPy)

np.dot() and np.matmul() (the @ operator) perform matrix multiplication and dot products. For 1-D arrays they compute the dot product; for 2-D arrays they do true matrix multiplication, not element-wise multiplication.

NumPy

It is vital to distinguish matrix multiplication from element-wise multiplication: A * B multiplies matching elements, while A @ B multiplies rows of A against columns of B following the rules of linear algebra. For two vectors, both np.dot and @ give the scalar dot product.

The @ operator (introduced for exactly this) is the modern, readable spelling of matmul and is preferred for matrix products. np.dot and np.matmul mostly agree, but they differ on stacks of matrices: matmul broadcasts the leading dimensions, treating the last two axes as the matrices.

Inner dimensions must line up: an (m, k) matrix times a (k, n) matrix gives an (m, n) result. Mismatched shapes are the usual error, so check that the columns of the left equal the rows of the right.

Syntax

A @ B  |  np.matmul(A, B)  |  np.dot(a, b)

Examples

Python

import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B)

Output:

[[19 22]
 [43 50]]

Learn it in a lesson

See also

Back to the Dictionary