给定两个指定的维度N1
和N2
,以及一些边界ymin、ymax、xmin、xmax
,我想构建一个 >N1xN2
矩阵(无论是 numpy 数组还是普通的 Python 列表),除由其边界指定的矩形子区域外,其余位置均为零。
更准确地说,我正在寻找如何实现一个函数rectangle_sparse_matrix(N1, N2, ymin, ymax, xmin, xmax)
,例如,
N1 = N2 = 5
rectangular_sparse_matrix(N1, N2, 0, 2, 1, 2)
返回
[[ 0 1 1 0 0]
[ 0 1 1 0 0]
[ 0 1 1 0 0]
[ 0 0 0 0 0]
[ 0 0 0 0 0]]
<小时/>
最简单的方法是循环遍历元素,就像
def rectangular_sparse_matrix(N1, N2, ymin, ymax, xmin, xmax):
matrix = np.zeros([N1, N2])
for row in range(N1):
for col in range(N2):
if ymin <= row <= ymax and xmin <= col <= xmax:
matrix[row, col] = 1
return matrix
它可以完成这项工作。 然而,我在想是否有一些更有效/更简单的方法来实现这样的事情,也许使用一些晦涩的(对我来说)numpy 功能或其他东西。
最佳答案
def rectangular_sparse_matrix(N1, N2, ymin, ymax, xmin, xmax):
m = np.zeros([N1, N2])
m[ymin:ymax+1, xmin:xmax+1] = 1
return m
在函数中使用切片 numpy 数组。
关于python - 定义仅在矩形子区域中具有非零元素的二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142199/