Numpy 将数组乘以矩阵(外积) [英] Numpy multiply arrays into matrix (outer product)

查看:29
本文介绍了Numpy 将数组乘以矩阵(外积)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个形状为 (5,1) 的 numpy 数组说:a=[1,2,3,4,5]b=[2,4,2,3,6]

I have 2 numpy arrays of shape (5,1) say: a=[1,2,3,4,5] b=[2,4,2,3,6]

如何制作一个矩阵,将每个第 i 个元素与每个第 j 个元素相乘?喜欢:

How can I make a matrix multiplying each i-th element with each j-th? Like:

..a = [1,2,3,4,5]
b 
2    2, 4, 6, 8,10
4    4, 8,12,16,20
2    2, 4, 6, 8,10
3    3, 6, 9,12,15
6    6,12,18,24,30

不使用forloops?我可以使用重塑、归约或乘法的任何组合吗?

Without using forloops? is there any combination of reshape, reductions or multiplications that I can use?

现在我沿着行和列创建每个数组的 a*b 平铺,然后将元素相乘,但在我看来必须有更简单的方法.

Right now I create a a*b tiling of each array along rows and along colums and then multiply element wise, but it seems to me there must be an easier way.

推荐答案

With numpy.outer()numpy.transpose() 例程:

With numpy.outer() and numpy.transpose() routines:

import numpy as np

a = [1,2,3,4,5]
b = [2,4,2,3,6]
c = np.outer(a,b).transpose()

print(c)

<小时>

或者只是交换数组顺序:


Or just with swapped array order:

c = np.outer(b, a)

<小时>

输出;

[[ 2  4  6  8 10]
 [ 4  8 12 16 20]
 [ 2  4  6  8 10]
 [ 3  6  9 12 15]
 [ 6 12 18 24 30]]

这篇关于Numpy 将数组乘以矩阵(外积)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆