How do I element-wise multiply an array of 6 elements with an array of 12 elements with the smaller array repeating?

Viewed 59

I have an array [x1, x2, x3, x4, x5, x6] and another array [y1, y2, y3,...y12].

I want to element-wise multiply the two arrays so that I get an array like: [x1*y1, x2*y2....x1*y7, x2*y8...x6*y12]

I thought numpy broadcasting would take care of it but it needs them to be the same shape.

2 Answers

np.resize

x = np.array([1, 2, 3])
y = np.array([1, 2, 3, 4, 5, 6])

np.resize(x, y.size) * y

array([ 1,  4,  9,  4, 10, 18])

np.resize will even work if the length of y is not a multiple of the length of x. It will keep filling in values from x, cycling through them until a length matching that of y is achieved.

x = np.array([1, 2, 3])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8])

np.resize(x, y.size) * y

array([ 1,  4,  9,  4, 10, 18,  7, 16])

Try itertools.cycle, zip, and listcomp

from itertools import cycle

x = np.arange(1,6)
y = np.arange(1,12)

list(zip(cycle(x), y))

Out[1758]:
[(1, 1),
 (2, 2),
 (3, 3),
 (4, 4),
 (5, 5),
 (1, 6),
 (2, 7),
 (3, 8),
 (4, 9),
 (5, 10),
 (1, 11)]


[i*j for i, j in zip(cycle(x), y)]

Out[1759]: [1, 4, 9, 16, 25, 6, 14, 24, 36, 50, 11]
Related