【问题标题】:k-neighbors of a given matrix M x N给定矩阵 M x N 的 k 个邻域
【发布时间】:2014-02-09 14:03:25
【问题描述】:

我正在尝试编写一个代码,给定整数矩阵的位置 (x,y),我可以遍历距离 K 的所有邻居(左、右、上、下和对角线),这样:

K = 1

01 02 03 04 05 06
07 08 09 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30

for i in range(M):
for j in range(N):
for ... #loop that i am writing... <br/>
#for (0,0) is [(0,0), (0,1), (1,0), (1, 1)]
#for (3, 3) is [(2,2), (2,3), (2,4), (3,2), (3,3), (3,4), (4,2), (4,3), (4,4)

这种方式适用于矩阵中的所有位置。

任何提示或代码?

【问题讨论】:

  • 是的,+k 和 -k 到索引

标签: python matrix nearest-neighbor


【解决方案1】:

Numpy 切片将使这变得非常简单

>>> import numpy as np
>>> a = np.array(range(25)).reshape((5,5))
>>> print a
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]
>>> k = 1
>>> a[2, 3]
13
>>> a[2-k:2+k+1, 3-k:3+k+1]

array([[ 7,  8,  9],
       [12, 13, 14],
       [17, 18, 19]])

Be careful of edge-cases, where index -1 will wrap to the other side of the array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多