carl
carl

Reputation: 4426

how to turn three 1D arrays into one 3D array by calculating the euclidian metric

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

Answers (2)

Mad Physicist
Mad Physicist

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

Quang Hoang
Quang Hoang

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

Related Questions