numpy.matmul¶

numpy.
matmul
(x1, x2, /, out=None, *, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'matmul'>¶ Matrix product of two arrays.
Parameters:  x1, x2 : array_like
Input arrays, scalars not allowed.
 out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)>(n,m). If not provided or None, a freshlyallocated array is returned.
 **kwargs
For other keywordonly arguments, see the ufunc docs.
 ..versionadded:: 1.16
Now handles ufunc kwargs
Returns:  y : ndarray
The matrix product of the inputs. This is a scalar only when both x1, x2 are 1d vectors.
Raises:  ValueError
If the last dimension of a is not the same size as the secondtolast dimension of b.
If a scalar value is passed in.
See also
Notes
The behavior depends on the arguments in the following way.
 If both arguments are 2D they are multiplied like conventional matrices.
 If either argument is ND, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
 If the first argument is 1D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed.
 If the second argument is 1D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.
matmul
differs fromdot
in two important ways:Multiplication by scalars is not allowed, use
*
instead.Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature
(n,k),(k,m)>(n,m)
:>>> a = a = np.full([9,5,7,3], True, dtype=bool) >>> c = np.full([9, 5, 4,3], True, dtype=bool) >>> np.dot(a, c).shape (9, 5, 7, 9, 5, 4) >>> np.matmul(a, c).shape # n is 5, k is 3, m is 4 (9, 5, 7, 4)
The matmul function implements the semantics of the @ operator introduced in Python 3.5 following PEP465.
Examples
For 2D arrays it is the matrix product:
>>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([[4, 1], ... [2, 2]] >>> np.matmul(a, b) array([[4, 1], [2, 2]])
For 2D mixed with 1D, the result is the usual.
>>> a = np.array([[1, 0], ... [0, 1]] >>> b = np.array([1, 2]) >>> np.matmul(a, b) array([1, 2]) >>> np.matmul(b, a) array([1, 2])
Broadcasting is conventional for stacks of arrays
>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4)) >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2)) >>> np.matmul(a,b).shape (2, 2, 2) >>> np.matmul(a, b)[0, 1, 1] 98 >>> sum(a[0, 1, :] * b[0 , :, 1]) 98
Vector, vector returns the scalar inner product, but neither argument is complexconjugated:
>>> np.matmul([2j, 3j], [2j, 3j]) (13+0j)
Scalar multiplication raises an error.
>>> np.matmul([1,2], 3) Traceback (most recent call last): ... ValueError: matmul: Input operand 1 does not have enough dimensions ...
New in version 1.10.0.