2013-11-22 216 views
0

(在下面的例子中6×6)有nxn的的一個特別的方式填充矩陣僅與0和1:調整大小的矩陣

old_matrix=[[0,0,0,1,1,0], 
      [1,1,1,1,0,0], 
      [0,0,1,0,0,0], 
      [1,0,0,0,0,1], 
      [0,1,1,1,1,0], 
      [1,0,0,1,1,0]] 

欲調整它以特定的方式。以(2x2)子矩陣和檢查是否有更多的1或零。這意味着新的矩陣將是(3x3)如果有多於1個子矩陣,則將在新矩陣中分配1個值。否則,(如果有或更少)其新值將爲0.

new_matrix=[[0,1,0], 
      [0,0,0], 
      [0,1,0]] 

我試圖通過使用大量的whiles來實現此目的。但它似乎並不奏效。這是我走到這一步:

def convert_track(a): 

    #converts original map to a 8x8 tile Track 

    NEW_TRACK=[] 
    w=0 #matrix width 
    h=0 #matrix heigth 
    t_w=0 #submatrix width 
    t_h=0 #submatrix heigth 
    BLACK=0 #number of ones in submatrix 
    WHITE=0 #number of zeros in submatrix 
    while h<=6: 
     while w<=6: 
      l=[] 
      while t_h<=2 and h<=6: 
       t_w=0 
       while t_w<=2 and w<=6: 
        if a[h][w]==1: 
         BLACK+=1 
        else: 
         WHITE+=1 
        t_w+=1 
        w+=1 
        h+=1 
        t_h+=1 
       t_w=0 
       t_h+=1 
      if BLACK<=WHITE: 
       l.append(0) 
      else: 
       l.append(1) 
      BLACK=0 
      WHITE=0 
      t_h=0  
     NEW_TRACK.append(l) 
    return NEW_TRACK 

引發錯誤列表索引超出範圍或返回列表

[[0]] 

有更簡單的方式來實現這一目標?我究竟做錯了什麼?

+1

有效的子矩陣將是第一個列表或行的前兩個元素,以及第二個列表或行的前兩個元素:[[0,0],[1,1]] –

回答

1

如果你願意/能夠使用NumPy你可以做這樣的事情。如果您正在處理類似於您所顯示的數據的任何內容,那麼非常值得花時間學習,因爲像這樣的操作可以非常有效地完成,而且代碼非常少。

import numpy as np 
from scipy.signal import convolve2d 

old_matrix=[[0,0,0,1,1,0], 
      [1,1,1,1,0,0], 
      [0,0,1,0,0,0], 
      [1,0,0,0,0,1], 
      [0,1,1,1,1,0], 
      [1,0,0,1,1,0]] 

a = np.array(old_matrix) 
k = np.ones((2,2)) 

# compute sums at each submatrix 
local_sums = convolve2d(a, k, mode='valid') 

# restrict to sums corresponding to non-overlapping 
# sub-matrices with local_sums[::2, ::2] and check if 
# there are more 1 than 0 elements 
result = local_sums[::2, ::2] > 2 

# convert back to Python list if needed 
new_matrix = result.astype(np.int).tolist() 

結果:

>>> result.astype(np.int).tolist() 
[[0, 1, 0], [0, 0, 0], [0, 1, 0]] 

在這裏,我用convolve2d計算在每個子矩陣的款項。從我可以告訴你只對非重疊的子矩陣感興趣,所以local_sums[::2, ::2]部分只剔出與那些相對應的和。

+0

真的很不錯的解決方案。那麼Numpy值得學習這種操作嗎? –

+1

肯定是的。或Matlab /八度。但其他所有條件都相同(即,您不必使用現有的Matlab代碼),NumPy最好學習。 – YXD