【问题标题】:Is there a way to select a subset of a Numpy 2D array using the Manhattan distance?有没有办法使用曼哈顿距离选择 Numpy 2D 数组的子集?
【发布时间】:2021-11-05 16:49:45
【问题描述】:

例如,我有一个用零填充的 Numpy 二维数组(7 行 7 列):

my_array = numpy.zeros((7, 7))

然后为了论证,我想选择中间的元素并将其值设置为1:

my_array[3,3] = 1

现在假设我的曼哈顿距离为 3,如何对数组进行子集化以仅选择小于或等于曼哈顿距离(从中间元素开始)的元素并将这些元素设置为 1?最终结果应该是:

我可以遍历二维数组中的每个元素,但不想这样做,因为这太昂贵了,特别是如果我的矩阵非常大而曼哈顿距离非常小(例如 70x70 矩阵,曼哈顿距离为10).

【问题讨论】:

    标签: python arrays numpy subset manhattan


    【解决方案1】:

    我将使用网格创建一个大小为 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)

    【讨论】:

    • 如果大小 N 大于 50(变化在 20 到 50 之间),它比 double 快大约 10 倍
    • 您好,感谢您的回答!我会在我的 jupyter notebook 上试试这个,然后给你反馈:)
    • 希望对您有所帮助!我有一些代码测试速度。请记住,如果您想访问原始矩阵,您可以使用elems 作为掩码,如matrix[elems],如果您想获取索引,然后点id_x,id_y = np.where(elems),然后indices = np.array([id_x,id_y]).T,那么您将获得indices[0], indices[1],.... 的对跨度>
    • 太棒了!!这解决了我的问题。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多