根据两个向量的差填充numpy矩阵 [英] Populate numpy matrix from the difference of two vectors
问题描述
是否可以从函数构造numpy
矩阵?在这种情况下,该函数特别是两个向量的绝对差:S[i,j] = abs(A[i] - B[j])
.一个使用常规python的最小工作示例:
Is it possible to construct a numpy
matrix from a function? In this case specifically the function is the absolute difference of two vectors: S[i,j] = abs(A[i] - B[j])
. A minimal working example that uses regular python:
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
S = np.zeros((3,3))
for i,x in enumerate(A):
for j,y in enumerate(B):
S[i,j] = abs(x-y)
给予:
[[ 1. 3. 5.]
[ 1. 1. 3.]
[ 4. 2. 0.]]
最好有一个看起来像这样的结构
It would be nice to have a construction that looks something like:
def build_matrix(shape, input_function, *args)
我可以在其中传递带有参数的输入函数,并保留numpy的速度优势.
where I can pass an input function with it's arguments and retain the speed advantage of numpy.
推荐答案
我建议您看一下numpy的广播功能:
I recommend taking a look into numpy's broadcasting capabilities:
In [6]: np.abs(A[:,np.newaxis] - B)
Out[6]:
array([[1, 3, 5],
[1, 1, 3],
[4, 2, 0]])
http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
然后,您可以简单地将函数编写为:
Then you could simply write your function as:
In [7]: def build_matrix(func,args):
...: return func(*args)
...:
In [8]: def f1(A,B):
...: return np.abs(A[:,np.newaxis] - B)
...:
In [9]: build_matrix(f1,(A,B))
Out[9]:
array([[1, 3, 5],
[1, 1, 3],
[4, 2, 0]])
对于大型阵列,这应该比您的解决方案要快得多.
This should also be considerably faster than your solution for larger arrays.
这篇关于根据两个向量的差填充numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!