Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 移动矩阵,使给定位置居中_Python_Numpy - Fatal编程技术网

Python 移动矩阵,使给定位置居中

Python 移动矩阵,使给定位置居中,python,numpy,Python,Numpy,您将获得一个nxnndarrayM和位置(x,y),目标是移动值,使c=(x,y)居中。“落在外面”的值将被删除,空空间将用零填充 例如: Input: M = 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 c = (0, 0) Output: 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 2 2 2 0 0 3 3 3 c = (3, 4) Output: 2 2 2 0 0 3 3 3 0 0

您将获得一个
nxn
ndarray
M
和位置
(x,y)
,目标是移动值,使
c=(x,y)
居中。“落在外面”的值将被删除,空空间将用零填充

例如:

Input: 

M =

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

c = (0, 0)

Output:

0 0 0 0 0
0 0 0 0 0
0 0 1 1 1
0 0 2 2 2
0 0 3 3 3

c = (3, 4)
 
Output:

2 2 2 0 0 
3 3 3 0 0
4 4 4 0 0 
5 5 5 0 0 
0 0 0 0 0 
numpy/scipy或python中的任何其他包中是否有任何函数


谢谢

我不知道有哪个numpy函数可以直接实现这一点,但您可以轻松编写一个:

def shift(M,c,r):
    w,h = M.shape
    return np.pad(M,((w,w),(h,h)),'constant')[w//2+1+c:,h//2+1+r:][:w,:h]
输出:

m = np.arange(1,6)[:,None]*np.ones(5).astype(np.int)
print(m)

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]
 [5 5 5 5 5]]


print(shift(m,0,0))

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

print(shift(m,3,4))

[[2 2 2 0 0]
 [3 3 3 0 0]
 [4 4 4 0 0]
 [5 5 5 0 0]
 [0 0 0 0 0]]

对于第二个输出,您是指
c=(3,4)
?在任何情况下,我不认为会有一个专门用于此的函数。当然,很高兴被证明是错的。这看起来很相关:@QuangHoang是的,对不起