有效地创建numpy数组,其中值越来越远离中心

时间:2018-02-28 04:12:16

标签: python numpy

var counterR = 0 var counterS = 0 for testing in (0..<sampLat.count) { let coordinates = CLLocation(latitude:sampLat[counterS], longitude:sampLong[counterS]) for testing1 in (0...refLat.count).reversed() { let coordinates2 = CLLocation(latitude:refLat[counterR], longitude:refLong[counterR]) let distanceInMeters = coordinates.distance(from: coordinates2) print("distance found",distanceInMeters) print("Counter Reference", counterR) if( distanceInMeters <= 50 ) { print("crossed check point", counterR) }else { print("out of range") } counterR = counterR + 1 print("---------------------------------------") } print("Counter Sample", counterS) counterS = counterS + 1 print("******************************************") } 为奇数正整数。我想创建一个形状为N的正方形2D网格,其中心元素为N x N,周围的8个邻域的值为N,该邻域周围的元素值为N-1等等,最后数组的“外壳”具有值N-2。我可以在for循环中使用N//2来完成此操作,迭代地将“shells”添加到数组中:

np.pad

示例输出:

def pad_decreasing(N):
    assert N % 2 == 1
    a = np.array([[N]])
    for n in range(N-1, N//2, -1):
        a = np.pad(a, 1, mode='constant', constant_values=n)
    return a

问题。我能否以“矢量化”形式完成此操作,而不是诉诸于循环。 In: pad_decreasing(5) Out: array([[3, 3, 3, 3, 3], [3, 4, 4, 4, 3], [3, 4, 5, 4, 3], [3, 4, 4, 4, 3], [3, 3, 3, 3, 3]]) 大的代码相当慢。

1 个答案:

答案 0 :(得分:4)

中心与网格中任意点之间的距离可写为np.maximum(np.abs(row - center), np.abs(col - center));然后 N 减去这个距离就会得到你需要的洋葱

N = 5

# the x and y coordinate of the center point
center = (N - 1) / 2

# the coordinates of the square array
row, col = np.ogrid[:N, :N]

# N - distance gives the result
N - np.maximum(np.abs(row - center), np.abs(col - center))

# array([[3, 3, 3, 3, 3],
#        [3, 4, 4, 4, 3],
#        [3, 4, 5, 4, 3],
#        [3, 4, 4, 4, 3],
#        [3, 3, 3, 3, 3]])