What is an alternative to unsupported NumPy function 'numpy.matmul'

This script runs fine in Python mode, but function f() fails to compile with Numba:

import numpy as np, numba as nb

@nb.njit(fastmath=True)
def f(mat, p):
  r = np.matmul(mat, p)
  return r[:-1]/r[-1]

mat = np.array([[  2.44 ,  -0.01 , -74.526],
                [  0.578,   0.873, -86.261],
                [  0.003,  -0.   ,   1.   ]])
q = [100, 200, 1]
print(f(mat, q))

producing this error:

numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Use of unsupported NumPy function 'numpy.matmul' or unsupported use of the function.

File "so-20.py", line 5:
def f(mat, p):
  r = np.matmul(mat, p)
  ^

Is there a workaround for this? I don’t have to use Numpy for matrix multiplication if there is another library, which works with Numba.

Hey @pauljurczak ,
Numba has implemented numpy.dot for operations on 1D and/or 2D arrays. You can use an operator like a @ b, too.

import numpy as np
import numba as nb

@nb.njit(fastmath=True)
def nb_dot(mat, q):
  return np.dot(mat, q)

@nb.njit(fastmath=True)
def nb_op(mat, q):
  return mat @ q

mat = np.array([[  2.44 ,  -0.01 , -74.526],
                [  0.578,   0.873, -86.261],
                [  0.003,  -0.   ,   1.   ]])
q = np.array([100., 200, 1])
print(np.matmul(mat, q))
print(nb_dot(mat, q))
print(nb_op(mat, q))
# [167.474 146.139   1.3  ]
# [167.474 146.139   1.3  ]
# [167.474 146.139   1.3  ]
1 Like

Thanks a lot. That’s what I was looking for.