Issue
the following is what I want to achieve. Is there a way to do this efficiently with Numpy or other methods in Python? Since my data would be big. I would like to do it more efficiently. Thank you in advance.
import numpy as np
x = np.arange(6).reshape(3,2)
y = np.arange(10).reshape(5,2)
z = np.zeros((len(x), len(y)))
for i in range(len(z)):
for j in range(len(z[0])):
z[i,j] = np.prod(x[i] - y[j])
Solution
Just vectorize your code:
z = (x[:,None]-y).prod(axis=-1)
Output:
array([[ 0, 4, 16, 36, 64],
[ 4, 0, 4, 16, 36],
[16, 4, 0, 4, 16]])
Intermediate:
(x[:,None]-y).
array([[[ 0, 0],
[-2, -2],
[-4, -4],
[-6, -6],
[-8, -8]],
[[ 2, 2],
[ 0, 0],
[-2, -2],
[-4, -4],
[-6, -6]],
[[ 4, 4],
[ 2, 2],
[ 0, 0],
[-2, -2],
[-4, -4]]])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.