我需要根据行/列索引和切片距离来切片 2D 输入数组。在下面的示例中,我可以从输入矩阵中提取 3x3 子矩阵,但我无法调整此代码以适应我想要的任何搜索距离,而无需手动写下索引:
Example:
import numpy as np
# create matrix
mat_A = np.arange(100).reshape((10, 10))
row = 5
col = 5
# Build 3x3 matrix around the centre point
matrix_three = ((row - 1, col - 1),
(row, col - 1),
(row + 1, col - 1),
(row - 1, col),
(row, col), # centre point
(row + 1, col),
(row - 1, col + 1),
(row, col + 1),
(row + 1, col + 1))
list_matrix_max_values = []
for loc in matrix_three:
val = mat_A[loc[0]][loc[1]]
list_matrix_max_values.append(val)
submatrix = np.matrix(list_matrix_max_values)
print(submatrix)
Returns:
[[44 54 64 45 55 65 46 56 66]]
例如,如果我想提取由行/列索引定义的单元格周围的 5x5 矩阵,我该如何做同样的事情?
提前致谢!