我将尝试用一个简单的例子来解释我所追求的。
aGrid = np.arange(1,9)
bGrid = np.arange(101, 109, 0.5)
A, B = np.meshgrid(aGrid, bGrid, indexing='ij')
np.random.seed(66)
valid = np.random.choice([True, False], A.shape)
将valid
想象成一个矩阵,决定你是否“允许停留在网格点(a, b)
。如果你不允许停留在那里,你必须通过减少 b
来移动:你需要向左移动(沿着行)。
我现在正在尝试创建这个 transition
矩阵:对于这个 valid
矩阵中的每一个项目,它决定了你需要走的“行程距离”,直到你到达下一个 True
项。行进距离来自元素之间的单位。在此示例中,我已将沿 b
维度的行进距离常数设置为 0.5
。如果您已经位于 True
位置,则您的距离为 0
。
这是给定种子的有效
:
array([[False, True, True, True, True, True, False, True, True,
True, True, False, False, True, False, True],
[ True, True, True, True, True, False, True, False, True,
True, True, True, True, False, True, False],
[ True, True, False, True, False, False, False, True, True,
True, True, True, False, False, True, False],
[ True, True, False, False, True, False, False, False, False,
False, False, True, False, False, True, False],
[ True, True, True, True, True, True, True, False, True,
True, False, False, False, False, False, True],
[False, True, True, False, False, True, True, False, True,
True, False, True, False, False, False, False],
[ True, True, True, False, True, False, True, True, True,
False, False, True, False, True, False, True],
[False, True, False, False, True, False, True, True, False,
True, False, False, False, True, False, False]], dtype=bool)
一些预期的输出
对于第一个元素,我们不能向左移动更多以找到 True
值 - 默认值应该是 np.NaN
。对于第一行接下来的 5 个元素,距离为 0
:它们已经位于有效位置。 transition[0, 6] = 0.5
: 需要向左移动一个元素。
所以,前两行是
array([[NaN, 0, 0, 0, 0, 0, 0.5, 0, 0,
0, 0, 0.5, 1, 0, 0.5, 0],
[ 0, 0, 0, 0, 0, 0.5, 0, 0, 0,
0, 0, 0, 0, 0.5, 0, 0.5],
我试图使用 np.argmax
和 np.argmax
的组合来找到“True
的最大元素,但更小x
,对于每个 x
,同时迭代 valid
中的每个元素 x
。这似乎效率极低。解决这个问题的更好方法是什么?
也许有一种方法可以将其矢量化?此外,我不能依赖于此示例中给出的 0.5
的等距离。该方法需要使用 bGrid
(或 B
)计算当前单元格与下一个有效单元之间的距离。
最佳答案
这似乎可以解决问题:
transition = np.array(valid, dtype=float)
for i in range(valid.shape[0]):
for j in range(valid.shape[1]):
transition[i, j] = 0 if valid[i, j] else transition[i, j-1] + bGrid[j] - bGrid[j-1] if j > 0 else np.NAN
关于python - 计算 "distance matrix",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29080184/