块状乘以不同的形状 [英] Numpy multiplying different shapes
本文介绍了块状乘以不同的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两个像这样的数组
x = [a,b]
y = [p,q,r]
我需要将此乘以一个乘积c
,它应该像这样,
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]
但是x*y
出现以下错误,
ValueError: operands could not be broadcast together with shapes (2,) (3,)
我可以做这样的事情,
for i in range(len(x)):
for t in range(len(y)):
c.append(x[i] * y[t]
但是我的x
和y
的长度确实很大,所以在没有循环的情况下进行这种乘法的最有效方法是什么.
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.
推荐答案
You can use NumPy broadcasting
for pairwise elementwise multiplication between x
and y
and then flatten with .ravel()
, like so -
(x[:,None]*y).ravel()
或使用 outer product
,然后将其展平-
Or use outer product
and then flatten -
np.outer(x,y).ravel()
这篇关于块状乘以不同的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文