2016-10-08 3 views
0

行列から特定の大きさのベクトルを抽出したいのですが、どのようにすればいいですか?私はMathWorks社のMATLABでwkeepとまったく同じことを何かを探していますPythonでmatlabのwkeepに相当するものは何ですか?

+0

することができますいくつかの方法があります'wkeep'を呼び出します。 'wkeep'の機能のどの要素を探していますか? – Praveen

+0

これは具体的には 'Y = wkeep(X、L)'です。 – Metal

+0

'X 'にはいくつのディメンションがありますか? – Praveen

答えて

3

それはwkeepのユースケースの多くは、よりidomatically書き込むことができることが判明:

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]]) 
関連する問題