Home > Software design >  Multiply 3D array with vectors in all three dimensions in Python
Multiply 3D array with vectors in all three dimensions in Python

Time:10-11

I am trying to multiply 3D array f by vectors x, y and z in all three dimensions.

import numpy as np

f = np.ones((2, 3, 4))

x = np.linspace(0, 10, 2)
y = np.linspace(0, 10, 3)
z = np.linspace(0, 10, 4)

print(z * f)
print(y[:, None] * f)
print((x * f.T).T)

Is there another way to achieve the last line without having to transpose f twice?

CodePudding user response:

I suppose that you are asking about broadcasting. If so, then reshaping x solves the problem:

f * x[:,None,None]
f * x.reshape(-1, 1, 1)

All we do here is alinging 1-dimentional vector with the dimension of the matrix f we are interested in (the same, as you do with y[:, None] * f).

  • Related