0
votes

have two arrays that are like this

x = [a,b]
y = [p,q,r]

I need to multiply this together to a product c which should be like this,

c = [a*p, a*q, a*r, b*p, b*q, b*r]

However x*y gives the following error,

ValueError: operands could not be broadcast together with shapes (2,) (3,)

I can do something like this,

for i in range(len(x)):
    for t in range(len(y)):
        c.append(x[i] * y[t]

But really the length of my x and y is quite large so what's the most efficient way to make such a multiplication without the looping.

2
Where a, b, p, q etc are scalars or something else? - Divakar
@Divakar they are floats so I suppose they are scalars isn't it? - rksh
It seems that you've missed a*r - kasravnd
@Kasramvd edited :) - rksh

2 Answers

5
votes

You can use NumPy broadcasting for pairwise elementwise multiplication between x and y and then flatten with .ravel(), like so -

(x[:,None]*y).ravel()

Or use outer product and then flatten -

np.outer(x,y).ravel()
0
votes

Use Numpy dot...

>>> import numpy as np
>>> a=np.arange(1,3)# [1,2]
>>> b=np.arange(1,4)# [1,2,3]
>>> np.dot(a[:,None],b[None])
array([[1, 2, 3],
       [2, 4, 6]])
>>> np.dot(a[:,None],b[None]).ravel()
array([1, 2, 3, 2, 4, 6])
>>>