pythonnumpy

What's the difference between @ and * with python matrix multiplication?


I know one does one kind of matrix multiplication and the other does another kind but can never remember the difference.

Doing

>>> import numpy as np
>>> a = np.matrix([[1, 2],[3,4]])

>>> print(a * a)
[[ 7 10]
 [15 22]]

>>> print(a @ a)
[[ 7 10]
 [15 22]]

appears to give the same answer which confuses me.


Solution

  • a * b is a multiplication operator - it will return elements in a multiplied by elements in b.

    When a and b are both matrices (specifically defined by np.matrix) the result will be the same as the @ operator.

    a @ b is matrix multiplication (dot product when used with vectors). If you haven't specified that a is a matrix and have used an array instead, a * a would return every element in a squared.