Reputation: 191
Suppose I have my own multiplication between two Python objects a
and b
, let's call it my_multiplication(a, b)
.
How can I perform a matrix multiplication using numpy where my_multiplication
is performed instead of the usual *
? Is that even possible?
Addendum: Would I still benefit from numpy's speed then?
Upvotes: 1
Views: 206
Reputation: 325
Try the numpy.dot
or the x.dot(y)
. See the documentation here
Example
import numpy as np
x = np.arange(12).reshape((3,4))
y = np.arange(4)
print(x,"\n\n",y,"\n")
print (np.dot(x,y))
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[0 1 2 3]
[14 38 62]
Upvotes: 0
Reputation: 19307
You can use np.vectorise on your function to get your custom multiplication function use all the usual numpy features such as broadcasting.
def my_multiplication(a, b):
#your code that works on multiplying 2 numbers
return c
v_my_multiplication = np.vectorize(my_multiplication)
v_my_multiplication([1, 2, 3], [1, 6])
#Will now work for np.array instead of just 2 numbers and utilize the broadcasting and vectorized implementation benefits that numpy has to offer.
Upvotes: 1