Reputation: 4426
I have three arrays:
x_array = [1., 2., 3.]
y_array = [1., 2., 3.]
z_array = [1., 2., 3.]
These 3 arrays define the axis for a 3D array. I would like to calculate the Euclidian metric like
array3D = np.array((3, 3, 3))
for ix in range(0, 3):
for iy in range(0, 3):
for iz in range(0, 3):
dist = np.sqrt(x_array[ix]**2 + y_array[iy]**2 + z_array[iz]**2)
array3D[ix][iy][iz] = dist
Is there a faster way than three for
loops?
Upvotes: 1
Views: 114
Reputation: 114230
For completeness, you can use np.add.outer
:
np.sqrt(np.add.outer(np.add.outer(x**2, y**2), z**2))
Upvotes: 1
Reputation: 150735
Try broadcasting:
a = np.sqrt(np.array(x_array)[:,None,None]**2
+ np.array(y_array)[None,:,None]**2
+ np.array(z_array)**2
)
Upvotes: 1