以下代码适用于非常具体的情况,如下所述。我想概括一下。我正在尝试打印出阵列的子数组。
import numpy as np
alpha = input("input this number... ")
X = np.arange(alpha**2).reshape(alpha,alpha) #square matrix
beta = input("a number in the matrix X")
if(beta > alpha**2):
print("must pick number inside array"), exit()
print(X) #correct square matrix
00 01 02 03 04
05 06 07 08 09
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
我想打印这个矩阵X的3x3子数组,与我选择的alpha无关(独立于3x3方形或5x5方形矩阵等)。如下图所示。
答案 0 :(得分:1)
您可以尝试:
import numpy as np
alpha = input("input this number... ")
X = np.arange(alpha**2).reshape(alpha,alpha) #square matrix
beta = input("a number in the matrix X")
if(beta > alpha**2):
print("must pick number inside array"), exit()
row, col = beta // alpha, beta % alpha # This will give you the idxs of beta number in array
subsize = input("a size of submatrix you want to get")
border = (subsize - 1) // 2
subrand = np.array(X)[row - border: row + border + 1, col - border: col + border + 1]
print(subrand)
答案 1 :(得分:1)
如果数组中的所有值都是唯一的(正如您在问题中的两个示例中所示):
[[i,j]] = numpy.argwhere(X==beta)
print(X[i-1:i+2,j-1:j+2])
此代码在2D数组中查找(i, j)
索引,使X[i,j]
等于beta
值。因此X[i-1:i+2,j-1:j+2]
是3x3数组,中心值为beta
,除非beta
位于矩阵的边缘。
即使在边缘也能获得所有可用值:
print(X[max(i-1,0):i+2,max(j-1,0):j+2])