2D配列の入力が与えられたときに、各インデックスの隣接インデックスの最小値の行と列のオフセットを返す関数を書くことになっているという問題があります。行の各インデックスのオフセット用の 1 つの配列と、列のオフセット用の 1 つの配列。たとえば、インデックスの最も低い隣接セルが 1 行下で 1 列右にある場合、オフセットは 1,1 です。一番下の隣接セルが左側にある場合、オフセットは 0、-1 です。隣接するセルの中で最も低いセルである場合、オフセットは 0,0 です。
これを行うためのより速くて正しい方法を見つけることができなかったので、各インデックスを反復処理し、ポイント [i,j] の周囲のインデックスのどれが他のすべての周囲のインデックスよりも低いかを確認する while ループを作成しました。 a.all() を使用:
def findLowNhbr( terrain ):
"""Creates two 2D-arrays the shape of terrain consisting
of the offsets (row and column) to the neighbor with the minimum eleveation"""
rowOffset = np.zeros_like(terrain)
colOffset = np.zeros_like(terrain)
for i in range(len(terrain)):
if i == 0:
rowOffset[i] = 0
colOffset[i] = 0
elif i == (len(terrain)-1):
rowOffset[i] = 0
colOffset[i] = 0
else:
for j in range(len(terrain[i])):
if j == 0 or j == len(terrain[i])-1:
rowOffset[:,j] = 0
colOffset[:,j] = 0
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i-1,j-1]).all():
rowOffset[i,j] = -1
colOffset[i,j] = -1
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i,j-1]).all():
rowOffset[i,j] = 0
colOffset[i,j] = -1
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i+1,j-1]).all():
rowOffset[i,j] = 1
colOffset[i,j] = -1
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i-1,j]).all():
rowOffset[i,j] = -1
colOffset[i,j] = 0
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i+1,j]).all():
rowOffset[i,j] = 1
colOffset[i,j] = 0
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i-1,j+1]).all():
rowOffset[i,j] = -1
colOffset[i,j] = 1
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i,j]).all():
rowOffset[i,j] = 0
colOffset[i,j] = 1
elif (terrain[i-1:i+2,j-1:j+2]>=terrain[i+1,j+1]).all():
rowOffset[i,j] = 1
colOffset[i,j] = 1
else:
rowOffset[i,j] = 0
colOffset[i,j] = 0
return rowOffset, colOffset
実行には長い時間がかかりますが、実行されます。私が実際にこれを可能な限り最も効率的な方法で行っているとは想像できません。入力はありますか?