Multiply 3D array with vectors in all three dimensions in Python

Question:

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?

Asked By: Ruan

||

Answers:

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).

Answered By: Vitalizzare
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.