2016-10-26 12 views
2

mxm modulo nxn == 0である次元(nxn)の部分行列で構成される正方行列M(mxm)を与え、各サブマトリックス。NumPy:部分行列/ブロックと対応する行、列インデックスの最小値を求める

M:

M* = array([[ 5148, 8083], 
      [ 5148, 8083]], dtype=uint64) 

私は)(配列の形状を変更し、分を起動しようとしたが、それだけであなたができます:次のように最小値が返されると(4×4)

M = array([[19834, 29333, 29333, 33120], 
      [ 5148, 25560, 29393, 8083], 
      [ 5148, 29393, 25560, 8083], 
      [19958, 25748, 25748, 24506]], dtype=uint64) 

は、各部分行列mは、2×2です1つの軸でそうすること。

また、最小値の元のインデックスも取得したいと思いますが、M *を生成してから検索する必要があると仮定しました。

答えて

2

あなたが得4Dアレイ内の第二及び第四の軸であろうこれら二つの分割軸のうちの第2として2それぞれの長さ4D配列、その結果2つの中に二つの軸を分割することができ。次に、目的の出力のためにこれらの2つの軸に沿ってminimumを見つけるだけです。

したがって、実装は次のようなものになります -

m,n = M.shape 
out = M.reshape(m//2,2,n//2,2).min(axis=(1,3)) 

サンプル実行 -

In [41]: M 
Out[41]: 
array([[33, 26, 15, 53, 72, 53], 
     [12, 64, 28, 27, 58, 51], 
     [61, 42, 70, 92, 61, 95], 
     [35, 62, 48, 27, 53, 33]]) 

In [42]: m,n = M.shape 

In [43]: M.reshape(m//2,2,n//2,2).min(axis=(1,3)) 
Out[43]: 
array([[12, 15, 51], 
     [35, 27, 33]]) 

のために元の配列

に対応する各部分行列でargminsを取得しますそれらのargmを取得するイン、我々は、下記のようにいくつかの追加の作業を行う必要があります -

B = 2 # Blocksize 
m,n = M.shape 

# Reshape into 4D array as discussed for the previous problem 
M4D = M.reshape(m//B,B,n//B,B) 

# Bring the second and fourth axes together and then merge. 
# Then, get linear indices within each submatrix 
lidx = M4D.transpose(0,2,1,3).reshape(-1,n//B,B**2).argmin(-1) 

# Convert those linear indices into row, col indices corresponding 
# to submatrix and finally corresponding to the original array 
r,c = np.unravel_index(lidx,[B,B]) 
row = r + (B*np.arange(m//B)[:,None]) 
col = c + B*np.arange(n//B) 

サンプル入力、出力 -

In [170]: M 
Out[170]: 
array([[40, 91, 90, 72, 86, 44], 
     [63, 56, 20, 95, 60, 41], 
     [28, 50, 32, 89, 69, 46], 
     [41, 41, 33, 81, 30, 63]]) 

In [171]: np.column_stack((row.ravel(),col.ravel())) 
Out[171]: 
array([[0, 0], 
     [1, 2], 
     [1, 5], 
     [2, 0], 
     [2, 2], 
     [3, 4]]) 
+0

は、各2x2の部分行列に対する最小値の「ローカル」座標を取得することが可能です?したがって、M [1、5]における最小値の座標は(1,1)となる。 psあなたのすばらしい助けと洞察力に感謝します。 – user1658296

+0

@ user1658296これは 'r、c'でしょう。 – Divakar

+0

私は参照してください。私は最終的に探しているのは、フォームの組みのセット(インスタンディング・コード、ローカル・コード、ミニマ)ですから、質問を更新する必要があると思います。例えば最小値M [1、5]については、ローカル座標は(1,1)であり、インスタンディング座標は(0,2)である。したがって、((0,2)、(1,1)、41) – user1658296

0

np.hsplitnp.vsplitを使用するとうまくいくと思います。

python3のmapmap objectを返しますので、さらに計算する前にmapの結果をリストする必要があります。

編集:第2の問題については、np.minnp.argminに変更すると、位置の行列が得られます。

import numpy as np 

M_star = np.array(list(map(lambda x: list(map(lambda x: np.min(x), x)), list(map(lambda x: np.hsplit(x, n), np.vsplit(M, n)))))) 
M_star_pos = np.array(list(map(lambda x: list(map(lambda x: np.argmin(x), x)), list(map(lambda x: np.hsplit(x, n), np.vsplit(M, n)))))) 
関連する問題