Reputation: 33202
Given a numpy array x
of shape (m,)
and a numpy array y
of shape (m/n,)
, how do I multiply x
by corresponding elements of y
efficiently?
Here's my best attempt:
In [13]: x = np.array([1, 5, 3, 2, 9, 1])
In [14]: y = np.array([2, 4, 6])
In [15]: n = 2
In [16]: (y[:, np.newaxis] * x.reshape((-1, n))).flatten()
Out[16]: array([ 2, 10, 12, 8, 54, 6])
Upvotes: 2
Views: 594
Reputation: 176810
Your solution looks pretty good to me.
If you wanted to speed it up slightly, you could:
Use ravel()
instead of flatten()
(the former will return a view if possible, the latter always returns a copy).
Reshape x
in Fortran order to avoid the overhead of another indexing operation on y
(although subsequent timings suggest this speedup is negligible)
So rewritten the multiplication becomes:
>>> (x.reshape((2, -1), order='f') * y).ravel('f')
array([ 2, 10, 12, 8, 54, 6])
Timings:
>>> %timeit (y[:, np.newaxis] * x.reshape((-1, n))).flatten()
100000 loops, best of 3: 7.4 µs per loop
>>> %timeit (x.reshape((n, -1), order='f') * y).ravel('f')
100000 loops, best of 3: 4.98 µs per loop
Upvotes: 3