Reputation: 23
I want to apply a function to each row in a vector. Even on a simple example like the one below I cant get it to work.
I make a function that takes two vectors and applies the dot product to them.
import numpy as np
def func(x,y):
return np.dot(x,y)
y=np.array([0, 1, 2])
x=np.array([0, 1, 2])
print(func(x,y))
Of course the output is 5. Now I want to plug in multiple vectors x, and get a solution back for each one. I dont want to use a for loop, so I tried using the vectorize function. For instance below I define X=(x1,x2,x3) and I want the output func(X,y)=(func(x1,y), func(x2,y), func(x3,y)). Why doesn't the following code do that:
import numpy as np
def func(x,y):
return np.dot(x,y)
y=np.array([0, 1 , 2])
X=np.array([[0,0,0], [1,1,1], [2,2,2]])
vfunc=np.vectorize(func)
print(vfunc(X,y))
Upvotes: 0
Views: 440
Reputation: 30991
The first trick to do is to exclude y argument (it is a fixed value for all rows from x).
The second trick is to pass the signature: Both arguments are arrays and the result is a scalar.
So, to vectorize your function, run:
vfunc = np.vectorize(func, excluded=['y'], signature='(n),(n)->()')
Then, when you call vfunc(X,y)
, you will get:
array([0, 3, 6])
Upvotes: 1