计算向量中所有条目组合之间的差异

编程入门 行业动态 更新时间:2024-10-17 00:26:46
本文介绍了计算向量中所有条目组合之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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.)

更多推荐

计算向量中所有条目组合之间的差异

本文发布于:2023-11-30 07:20:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   向量   条目   差异

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!