2

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])
0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

I imagine the speed increase will be more pronounced for longer vectors.
@NeilG - you're right, a quick test for x of length 1000000 and y of length 500000 suggests it's faster by a factor of 10 (much more that I'd imagined). Most of the speedup comes from using ravel().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.