0

I have a 3D array and I have three 1D array, which represents the x-axis, y-axis, and z-axis values. I would like to multiply the 3D array with the 1D arrays. The correct value can be obtained with

   array_x = np.array([1,2,3])
   array_y = np.array([1,2,3])
   array_z = np.array([1,2,3])
   array3D = something
   for ix, x in enumerate(array_x):
       for iy, y in enumerate(array_y):
           for iz, z in enumerate(array_z):
               array3D[ix][iy][iz] *= x*y*z

What is the fastest way to do this in python? I would also like to avoid turning the three 1D arrays into 3D arrays since I need to keep the memory usage low.

1 Answer 1

3

You can extend each array along the dimension it is to be multiplied in:

>>> array3D = np.arange(27).reshape((3,3,3))
>>> (array3D*array_x)*array_y[:,None])*array_z[:, None, None]
# or using Einstein Summation convention (np.einsum)
# np.einsum('i, j, k, ijk -> ijk',array_x, array_y, array_z, array3D)

array([[[  0,   2,   6],
        [  6,  16,  30],
        [ 18,  42,  72]],

       [[ 18,  40,  66],
        [ 48, 104, 168],
        [ 90, 192, 306]],

       [[ 54, 114, 180],
        [126, 264, 414],
        [216, 450, 702]]])

Which is the same answer as your nested loop code, but much faster.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.