tamasgal
tamasgal

Reputation: 26259

Multiply two arrays with different dimensions using numpy

I need a faster/optimised version of my current code:

import numpy as np

a = np.array((1, 2, 3))
b = np.array((10, 20, 30, 40, 50, 60, 70, 80))

print([i*b for i in a])

Is there any faster way to do this using numpy functions (maybe without reshaping and blowing up the whole thing)?

Upvotes: 1

Views: 5738

Answers (1)

kennytm
kennytm

Reputation: 523184

Looks like the outer product.

>>> np.outer(a, b)
array([[ 10,  20,  30,  40,  50,  60,  70,  80],
       [ 20,  40,  60,  80, 100, 120, 140, 160],
       [ 30,  60,  90, 120, 150, 180, 210, 240]])

Upvotes: 11

Related Questions