matlab的wkeep在Python中的等价物是什么?

2024-04-19 18:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我想从矩阵中提取一定大小的向量,我该怎么做?你知道吗

我在寻找一个与matlab中的^{}完全相同的东西


Tags: 矩阵向量matlab
1条回答
网友
1楼 · 发布于 2024-04-19 18:22:18

事实证明,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]])

相关问题 更多 >