pythonnumpyvectorization

Vectorize a Numpy Function


For instance, I want to vectorize the function that returns a determinant of a matrix.

So I try the following codes:

data1test=np.random.rand(2,2)
data2test=np.random.rand(2,2)
data3test=np.random.rand(2,2)
data4test=np.random.rand(2,2)
fulldata=np.array((data1test,data2test,data3test,data4test))

def det_vec():
    return np.vectorize(np.linalg.det)
myfunc=det_vec()
myfunc(fulldata)

However, it returns a "LinAlgError: 0-dimensional array given. Array must be at least two-dimensional" error.

Can anyone show me what is the problem? Thank you!


Solution

  • Your vectorized function is vectorizing too deeply, it would seem.

    You can use the signature argument to get around this and force vectorization at only the top level:

    >>> myfunc = np.vectorize(np.linalg.det, signature="(a,b,c)->(a)")
    >>> myfunc((np.eye(2), np.array([[1,3],[4,2]])))
    array([  1., -10.])
    

    Edit: It's worth mentioning that @hpaulj is right - explicit vectorization isn't even necessarily needed here. See the following:

    >>> np.linalg.det((np.eye(2), np.array([[1,3],[4,2]])))
    array([  1., -10.])