将Numpy乘法数组转换成矩阵(外部乘积) [英] Numpy multiply arrays into matrix (outer product)
本文介绍了将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.
推荐答案
使用 numpy.transpose()例程:
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)
输出;
The output;
[[ 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屋!
查看全文