Make the matrix multiplication operator @ work for scalars in numpy
As ajcr suggested, you can work around this issue by forcing some minimal dimensionality on objects being multiplied. There are two reasonable options: atleast_1d and atleast_2d which have different results in regard to the type being returned by @
: a scalar versus a 1-by-1 2D array.
x = 3y = 5z = np.atleast_1d(x) @ np.atleast_1d(y) # returns 15 z = np.atleast_2d(x) @ np.atleast_2d(y) # returns array([[15]])
However:
- Using atleast_2d will lead to an error if x and y are 1D-arrays that would otherwise be multiplied normally
- Using atleast_1d will result in the product that is either a scalar or a matrix, and you don't know which.
- Both of these are more verbose than
np.dot(x, y)
which would handle all of those cases.
Also, the atleast_1d version suffers from the same flaw that would also be shared by having scalar @ scalar = scalar: you don't know what can be done with the output. Will z.T
or z.shape
throw an error? These work for 1-by-1 matrices but not for scalars. In the setting of Python, one simply cannot ignore the distinction between scalars and 1-by-1 arrays without also giving up all the methods and properties that the latter have.