[英]n x n matrix in numpy by applying function to pairs of elements in n x 1 numpy array
If I have an array in numpy a
which is nx 1
.如果我在 numpy
a
中有一个数组,它是nx 1
。 In addition, I have a function F(x,y)
which takes in two values and returns a single value.此外,我有一个 function
F(x,y)
,它接受两个值并返回一个值。 I want to construct an nxn
matrix b
where b_ij = F(a_i, a_j) (in the array a
).我想构造一个
nxn
矩阵b
,其中 b_ij = F(a_i, a_j) (在数组a
中)。 Is there any way to do this without looping over both arrays?有没有办法在不循环遍历 arrays 的情况下执行此操作?
Assume that your function is:假设你的 function 是:
def F(a_i, a_j):
return (a_i + a_j) if a_i % 2 == 0 else (a_i + a_j + 1)
To call it on 2 arrays in 1 go, define the vectorized version of this function:要在 2 arrays in 1 go 上调用它,请定义此 function 的矢量化版本:
FF = np.vectorize(F)
Then call it:然后调用它:
result = FF(a, a.T)
As the source array I used:作为我使用的源数组:
a = np.array([[1], [5], [10], [50], [80]])
so its shape is (5, 1) (a single-column array) and got:所以它的形状是(5, 1) (单列数组)并得到:
array([[ 3, 7, 12, 52, 82],
[ 7, 11, 16, 56, 86],
[ 11, 15, 20, 60, 90],
[ 51, 55, 60, 100, 130],
[ 81, 85, 90, 130, 160]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.