如果我想从矩阵中提取一定大小的矢量,我该怎么做?
我在matlab中寻找与wkeep
完全相同的东西
答案 0 :(得分:3)
事实证明wkeep
的许多用例可以更自然地编写:
X[1:3,1:4] # wkeep(X, [2, 3])
如果您实际上不需要居中,可以使用:
X[:2, :4] # wkeep(X, [2, 3], 'l')
X[-2:, -4:] # wkeep(X, [2, 3], 'r')
或者,如果您使用wkeep的真正原因是修剪边框:
X[2:-2,2:-2] # wkeep(X, size(X) - 2)
如果你真的想要wkeep(X,L)
的直接翻译,那么wkeep
似乎在做什么:
# 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]
例如:
>>> X = np.arange(20).reshape(4, 5)
>>> centered_slice(X, [2, 3])
array([[ 6, 7, 8],
[11, 12, 13]])