计算向量中所有条目组合之间的差异 [英] calculate difference between all combinations of entries in a vector

查看:124
本文介绍了计算向量中所有条目组合之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个z值的numpy 1D数组,我想计算所有条目组合之间的差,并将输出作为一个方矩阵。

I have a numpy 1D array of z values, and I want to calculate the difference between all combinations of the entries, with the output as a square matrix.

我知道如何使用cdist将其计算为所有点组合之间的距离,但这并没有给我以下符号:

I know how to calculate this as a distance between all combinations of the points using cdist, but that does not give me the sign:

例如,如果我的z向量为[1,5,8]

So for example if my z vector is [1,5,8]

import numpy as np
from scipy.spatial.distance import cdist

z=np.array([1, 5, 8])
z2=np.column_stack((z,np.zeros(3)))
cdist(z2,z2)

给我:

array([[0., 4., 7.],
       [4., 0., 3.],
       [7., 3., 0.]])

但我想有迹象给我:

array([[0., 4., 7.],
       [-4., 0., 3.],
       [-7., -3., 0.]])

我考虑过使用np.tril_indices翻转下三角形的符号来弄乱事物,但这是行不通的,因为我需要以一致的方式对两对进行区分(例如,如果我对两个或多个向量执行此操作,对是总是以相同的顺序进行比较),而通过翻转符号,我总是在右上方具有正差异,而在左下方则具有负差异。

I thought about fudging things by using np.tril_indices to flip the sign of the lower triangle, but this won't work, as I need the pairs to be differenced in a consistent way for my operation (i.e. if I perform this on two or more vectors, the pairs are always compared in the same order), whereas by flipping the sign I will always have positive differences in the upper right and negative in the lower left.

推荐答案

In [29]: z = np.array([1, 5, 8])                                                                                                                                                                     

In [30]: -np.subtract.outer(z, z)                                                                                                                                                                    
Out[30]: 
array([[ 0,  4,  7],
       [-4,  0,  3],
       [-7, -3,  0]])

(如果您不关心符号约定,请删除减号。)

(Drop the minus sign if you don't care about the sign convention.)

这篇关于计算向量中所有条目组合之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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