【问题标题】:Extract submatrix at certain row/col values在某些行/列值处提取子矩阵
【发布时间】:2018-06-28 00:28:55
【问题描述】:

我需要从行/列索引和切片距离中切片一个 2D 输入数组。在下面的示例中,我可以从输入矩阵中提取一个 3x3 子矩阵,但我无法调整此代码以适用于我想要的任何搜索距离,而无需手动记下索引:

例子:

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)

返回:

[[44 54 64 45 55 65 46 56 66]]

如果我想在我的行/列索引定义的单元格周围提取一个 5x5 矩阵,我该如何做同样的事情? 提前致谢!

【问题讨论】:

    标签: python matrix slice


    【解决方案1】:
    S=3 # window "radius"; S=3 gives a 5x5 submatrix
    mat_A[row-S+1:row+S,col-S+1:col+S]
    #array([[33, 34, 35, 36, 37],
    #       [43, 44, 45, 46, 47],
    #       [53, 54, 55, 56, 57],
    #       [63, 64, 65, 66, 67],
    #       [73, 74, 75, 76, 77]])
    

    【讨论】:

    • 完美!非常感谢! :)
    【解决方案2】:

    Numpy 具有矩阵切片功能,因此您可以对行和列进行切片。

    mat_A[4:7, 4:7]
    

    返回

      [[44, 45, 46],
       [54, 55, 56],
       [64, 65, 66]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      相关资源
      最近更新 更多