As an example, I have the 2 following 1d-arrays:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6])
Now, I need to multiply a
for each element of b
in order to obtain a 2d-array:
[[5 10 15 20],
[6 12 18 24]]
Now, I solved the problem by creating 2 new 2d-arrays by repeating either rows or columns and then performing the multiplication, i.e.:
a_2d = np.repeat(a[np.newaxis, :], b.size, axis=0)
b_2d = np.tile(b[:, np.newaxis], a.size)
print(a_2d*b_2d)
#[[ 5 10 15 20]
# [ 6 12 18 24]]
Is there a way to make this operation more efficient?
This would not be limited to multiplications only but, ideally, applicable to all 4 operations. Thanks a lot!
repeat
. Letbroadcasting
do the work.b[:,np.newaxis]*a