Python 使用numpy计算多条轨迹的成对距离

Python 使用numpy计算多条轨迹的成对距离,python,numpy,Python,Numpy,给定任意数量的3D轨迹,每个轨迹有N个点(时间步),我想计算给定时间步的每个点之间的距离 假设我们看一下时间步3,有四条轨迹t_0。。。图3。轨迹0的第三个时间步的点表示为t_0(3)。我想计算如下距离: d_0 = norm(t_0(3) - t_1(3)) d_1 = norm(t_1(3) - t_2(3)) d_2 = norm(t_2(3) - t_3(3)) d_3 = norm(t_3(3) - t_0(3)) 正如您所看到的,其中有一种循环行为(最后一个计算到第一个的距离),

给定任意数量的3D轨迹,每个轨迹有N个点(时间步),我想计算给定时间步的每个点之间的距离

假设我们看一下时间步3,有四条轨迹t_0。。。图3。轨迹0的第三个时间步的点表示为t_0(3)。我想计算如下距离:

d_0 = norm(t_0(3) - t_1(3))
d_1 = norm(t_1(3) - t_2(3))
d_2 = norm(t_2(3) - t_3(3)) 
d_3 = norm(t_3(3) - t_0(3))
正如您所看到的,其中有一种循环行为(最后一个计算到第一个的距离),但这并不是严格必要的

我知道如何编写一些for循环并计算我想要的。我要寻找的是一个概念,或者是一个numpy(或者np函数的组合)中的实现,它可以使用右轴和其他numpy魔术来执行这个逻辑

下面是一些示例轨迹

import numpy as np

TIMESTEP_COUNT = 70
origin = np.array([0, 0, 0])

run1_direction = np.array([1, 0, 0]) / np.linalg.norm([1, 0 ,0])
run2_direction = np.array([0, 1, 0]) / np.linalg.norm([0, 1, 0])
run3_direction = np.array([0, 0, 1]) / np.linalg.norm([0, 0, 1])
run4_direction = np.array([1, 1, 0]) / np.linalg.norm([1, 1, 0])

run1_trajectory = [origin]
run2_trajectory = [origin]
run3_trajectory = [origin]
run4_trajectory = [origin]

for t in range(TIMESTEP_COUNT - 1):
    run1_trajectory.append(run1_trajectory[-1] + run1_direction)
    run2_trajectory.append(run2_trajectory[-1] + run2_direction)
    run3_trajectory.append(run3_trajectory[-1] + run3_direction)
    run4_trajectory.append(run4_trajectory[-1] + run4_direction)

run1_trajectory = np.array(run1_trajectory)
run2_trajectory = np.array(run2_trajectory)
run3_trajectory = np.array(run3_trajectory)
run4_trajectory = np.array(run4_trajectory)
。。。结果显示在下图中:

提前谢谢你

编辑:
我的问题与下面的建议答案不同,因为我不想计算完整的距离矩阵。我的算法应该只处理连续运行之间的距离。

我认为可以将它们垂直堆叠,以获得一个形状
4 x n_时间步的数组,然后使用
np.roll
在每个时间步中进行差异,即:

r = np.vstack([t0,t1,t2,t3])
r - np.roll(r,shift=-1,axis=0)
数值示例:

t0,t1,t2,t3 = np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5)
r = np.vstack([t0,t1,t2,t3])
r
array([[1, 7, 7, 6, 2],
       [9, 1, 2, 3, 6],
       [1, 1, 6, 8, 1],
       [2, 9, 5, 9, 3]])

r - np.roll(r,shift=-1,axis=0)
array([[-8,  6,  5,  3, -4],
       [ 8,  0, -4, -5,  5],
       [-1, -8,  1, -1, -2],
       [ 1,  2, -2,  3,  1]])

那么
runX\u轨迹
是需要计算距离的数组吗?这是否回答了您的问题?也许您应该包括for循环实现来说明您正在尝试做什么。看起来你想做-
np.linalg.norm(run1\u轨迹-run2\u轨迹,axis=1)
scipy.spatial.distance.cdist(run1\u轨迹,run2\u轨迹)[:,1]
或<代码>w=scipy.space.distance.cdist(运行1\u轨迹,运行2\u轨迹);打印(带对角线()[:10])