Jundiaius
Jundiaius

Reputation: 7688

Outer product and flatten with vectorial operations - numpy

I am doing the following operation with a 2-d array m and a 1-d array v:

result = np.array([np.outer(v, m_row).flatten() for m_row in m])

However this is a lot slower than numpy pure vectorial operations, as I am using a list comprehension and a np.array at the end.

Can I do this outer product for each row in a matrix with only one operation? Or at least only using vectorial operations, without use of a loop or list comprehension?

Upvotes: 2

Views: 328

Answers (1)

Divakar
Divakar

Reputation: 221634

Extend dims and then use broadcasting -

(m[:, None, :]*v[:, None]).reshape(m.shape[0], -1)

Alternatively, with np.einsum -

np.einsum('ij,k->ikj', m, v).reshape(m.shape[0], -1)

For m of shape (30, 5) and v of shape (6,):

%timeit (m[:, None, :]*v[:, None]).reshape(m.shape[0], -1)
# 5.93 µs ± 77.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.einsum('ij,k->ikj', m, v).reshape(m.shape[0], -1)
# 5.44 µs ± 61.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.array([np.outer(v, m_row).flatten() for m_row in m])
# 179 µs ± 18.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Upvotes: 2

Related Questions