【问题标题】:Disable negative indexing when checking neighbours in a matrix in Python在 Python 中检查矩阵中的邻居时禁用负索引
【发布时间】:2021-08-30 04:57:08
【问题描述】:

所以我有以下带有给定输入的代码:

import numpy as np

x = np.matrix([[1,1,1,1,0],
               [1,1,1,0,0],
               [1,1,0,0,0],
               [1,0,0,0,0]])
print(x)

def MIZ(mat,check):
    for j in range(0,mat.shape[0]):
        for i in range(0,mat.shape[1]):
            try:
                if mat[i,j] == 1:
                    if mat[i+check,j] == 0 or \
                       mat[i-check,j] == 0 or \
                       mat[i,j+check] == 0 or \
                       mat[i,j-check] == 0:
                           mat[i,j] = 2
            except:
                pass
    return mat
            
print(MIZ(x,1))

这个想法很简单;因为位于 0 旁边的所有 1 都将转换为 2。此处的“check”参数理想情况下应该是可调整的,这样如果“check=2”,则有 0 个空格的 1 也将转换为 2,依此类推。现在问题出现在矩阵中的第一个元素(索引 = 0,0),因为那时 i-1 和 j-1 都是 -1,出于我的目的,我想避免这种情况并将其仅限于周围元素。

代码的当前结果是:

[[2 2 2 2 0]
 [2 1 2 0 0]
 [2 2 0 0 0]
 [1 0 0 0 0]]

还有最低的 1 没有被转换为 2 的问题,但这是次要问题。

【问题讨论】:

    标签: python numpy matrix indexing numpy-ndarray


    【解决方案1】:

    您可以在索引之前检查您是否在范围内。 就像那样(顺便说一句,我在循环中更改了 i 和 j):

    def in_range(index, range_length):
        return -range_length <= index <= range_length -1
    
    
    def MIZ(mat, check):
        for i in range(0, mat.shape[0]):
            for j in range(0, mat.shape[1]):
                if mat[i, j] == 1:
                    if (in_range(i+check, mat.shape[0]) and mat[i + check, j] == 0) or \
                       (in_range(i-check, mat.shape[0]) and mat[i - check, j] == 0) or \
                        (in_range(j + check, mat.shape[1]) and mat[i, j + check] == 0) or \
                        (in_range(j - check, mat.shape[1]) and mat[i, j - check] == 0):
                        mat[i, j] = 2
        return mat
    
    print(MIZ(x, 1))
    

    输入:

    x = np.array([[1,1,1,1,0],
                   [1,1,1,0,0],
                   [1,1,0,0,0],
                   [1,0,0,0,0]])
    

    输出:

    [[2 2 2 2 0]
     [2 1 2 0 0]
     [2 2 0 0 0]
     [2 0 0 0 0]]
    

    编辑,更改“in_range”函数应该使您只能根据需要访问非负索引:

    def in_range(index, range_length):
        return 0 <= index <= range_length -1
    

    输入:

    x = np.array([[1,1,1,1,0],
                   [1,1,1,0,0],
                   [1,1,0,0,0],
                   [1,0,0,0,0]])
    

    输出:

    [[1 1 1 2 0]
     [1 1 2 0 0]
     [1 2 0 0 0]
     [2 0 0 0 0]]
    

    【讨论】:

    • 嗨,虽然这肯定看起来更好,并解决了最低的 1 错误,同时消除了使用 try: 语句的需要 - 这一切都很好,但它仍然没有解决我的基本问题。因为我希望不与 0 接壤的顶部和左侧边缘的 1 保持为 1,例如第一行的第一个元素只被 1 包围,所以它不应该变成 2(它这样做是因为 x[-1,0] 和 x[0,-1] 为零,但我不希望它触发而只关注直接邻居)
    • 只是为了确保,预期的输出应该是:[[1 1 1 2 0] [1 1 2 0 0] [1 2 0 0 0] [2 0 0 0 0]] ?
    • 正确!是的,这就是我正在寻找的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2016-04-06
    相关资源
    最近更新 更多