# Matlab has this terrible habit of implementing general functions
# in specific packages, and naming after only their specific use case.
# let's pick a name that actually tells us what this does
def centered_slice(X, L):
L = np.asarray(L)
shape = np.array(X.shape)
# verify assumptions
assert L.shape == (X.ndim,)
assert ((0 <= L) & (L <= shape)).all()
# calculate start and end indices for each axis
starts = (shape - L) // 2
stops = starts + L
# convert to a single index
idx = tuple(np.s_[a:b] for a, b in zip(starts, stops))
return X[idx]
事实证明,
wkeep
的许多用例都可以更灵活地编写:如果实际上不需要居中,可以使用:
或者,如果使用wkeep的真正原因是修剪边界:
如果你真的想直接翻译
wkeep(X,L)
,下面是wkeep
应该做的:例如:
相关问题 更多 >
编程相关推荐