Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the matrix multiplication operator @ work for scalars in numpy

Tags:

People also ask

How do you multiply a matrix by a scalar in NumPy?

Numpy multiply array by scalar In order to multiply array by scalar in python, you can use np. multiply() method.

Which NumPy function is used to perform matrix multiplication?

First is the use of multiply() function, which perform element-wise multiplication of the matrix. Second is the use of matmul() function, which performs the matrix product of two arrays. Last is the use of the dot() function, which performs dot product of two arrays.

How does NumPy Matmul work?

The numpy. matmul() function returns the matrix product of two arrays. While it returns a normal product for 2-D arrays, if dimensions of either argument is >2, it is treated as a stack of matrices residing in the last two indexes and is broadcast accordingly.

What does the operator do in NumPy?

Using Arithmetic Operators with Numpy You can perform arithmetic operations on these arrays. For example, if you add the arrays, the arithmetic operator will work element-wise. The output will be an array of the same dimension. You can run an arithmetic operation on the array with a scalar value.


In python 3.5, the @ operator was introduced for matrix multiplication, following PEP465. This is implemented e.g. in numpy as the matmul operator.

However, as proposed by the PEP, the numpy operator throws an exception when called with a scalar operand:

>>> import numpy as np
>>> np.array([[1,2],[3,4]]) @ np.array([[1,2],[3,4]])    # works
array([[ 7, 10],
       [15, 22]])
>>> 1 @ 2                                                # doesn't work
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for @: 'int' and 'int'

This is a real turnoff for me, since I'm implementing numerical signal processing algorithms that should work for both scalars and matrices. The equations for both cases are mathematically exactly equivalent, which is no surprise, since "1-D x 1-D matrix multiplication" is equivalent to scalar multiplication. The current state however forces me to write duplicate code in order to handle both cases correctly.

So, given that the current state is not satisfactory, is there any reasonable way I can make the @ operator work for scalars? I thought about adding a custom __matmul__(self, other) method to scalar data types, but this seems like a lot of hassle considering the number of involved internal data types. Could I change the implementation of the __matmul__ method for numpy array data types to not throw an exception for 1x1 array operands?

And, on a sidenote, which is the rationale behind this design decision? Off the top of my head, I cannot think of any compelling reasons not to implement that operator for scalars as well.