块状乘以不同的形状

编程入门 行业动态 更新时间:2024-10-24 22:21:19
本文介绍了块状乘以不同的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有两个像这样的数组

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()

更多推荐

块状乘以不同的形状

本文发布于:2023-11-08 15:48:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569796.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:块状   形状

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!