本文介绍了块状乘以不同的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有两个像这样的数组
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.
推荐答案您可以使用 NumPy broadcasting 用于x和y之间的成对逐元素乘法,然后用.ravel()展平,就像这样-
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()更多推荐
块状乘以不同的形状
发布评论