从 python 中的两个向量构建比较矩阵
Build a matrix of comparisons out of two vectors in python
我有两个向量 a
和 b
,我想将 a
中的每个元素与 b
中的每个元素进行比较。作为比较的衡量标准,我想使用absolute difference。
最好的方法是什么,意思是没有 nested/double 循环?
插图:
a = [1,2,3]
b = [4,5,6]
calculation idea:
1 2 3
4 3 2 1
5 4 3 2
6 5 4 3
resulting matrix:
3 2 1
4 3 2
5 4 3
这样的计算怎么称呼?
import numpy as np
a = np.array(a)
b = np.array(b)
使用外部:
np.subtract.outer(b,a)
使用广播:
b[:,None]-a
我有两个向量 a
和 b
,我想将 a
中的每个元素与 b
中的每个元素进行比较。作为比较的衡量标准,我想使用absolute difference。
最好的方法是什么,意思是没有 nested/double 循环?
插图:
a = [1,2,3]
b = [4,5,6]
calculation idea:
1 2 3
4 3 2 1
5 4 3 2
6 5 4 3
resulting matrix:
3 2 1
4 3 2
5 4 3
这样的计算怎么称呼?
import numpy as np
a = np.array(a)
b = np.array(b)
使用外部:
np.subtract.outer(b,a)
使用广播:
b[:,None]-a