例如,我有一個 Numpy 2D 陣列(7 行,7 列),其中填充了零:
my_ 陣列 = numpy.zeros((7, 7))
然后為了論證,我想選擇中間的元素并將其值設定為 1:
my_array[3,3] = 1
現在假設我的曼哈頓距離為 3,我如何對陣列進行子集化以僅選擇小于或等于曼哈頓距離(從中間元素)的元素并將這些元素設定為 1?最終結果應該是:

我可以遍歷 2D 陣列中的每個元素,但不想這樣做,因為這太昂貴了,特別是如果我的矩陣非常大且曼哈頓距離非常小(例如,曼哈頓距離為 10 的 70x70 矩陣)。
uj5u.com熱心網友回復:
我會用meshgrid創建一個大小為2,n,n的輔助矩陣來合并索引,然后減去所需的索引中心,對減去的索引的絕對值求和并進行閾值比較。這里有一些例子
import numpy as np
import matplotlib.pyplot as plt #to draw result
n=70 #size of matrix
distance = 10 #distance
centerCoord = [35,35]
#here i create a mesh matrix of indices
xarr = np.arange(n)
idxMat = np.meshgrid(xarr,xarr) #create a matrix [2,n,n]
pt = np.array(centerCoord).reshape(-1,1,1) #point of size [2,1,1]
elems = np.abs(idxMat-pt).sum(axis=0) <= distance
plt.matshow(elems)
結果:

如果您需要索引,則呼叫np.where它將回傳 2 個陣列 (xindexList,yindexList)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350867.html
下一篇:scipy矩陣轉換檔案不清楚
