如何在numpy中获得给定大小的所有子矩阵?

时间:2015-09-21 19:53:53

标签: python numpy submatrix

例如,x = np.random.randint(low=0, high=10, shape=(6,6))给了我一个6x6的numpy数组:

array([[3, 1, 0, 1, 5, 4],
       [2, 9, 9, 4, 8, 8],
       [2, 3, 4, 3, 2, 9],
       [5, 8, 4, 5, 7, 6],
       [3, 0, 8, 1, 8, 0],
       [6, 7, 1, 9, 0, 5]])

如何获取所有2x3子矩阵的列表?那些非重叠的呢?

我可以自己编写代码,但我确定这是一个足够普通的操作,它已经存在于numpy中,我无法找到它。

1 个答案:

答案 0 :(得分:3)

本文中列出了获取给定形状的子矩阵列表的通用方法。根据子矩阵的行(C风格)或列专业(fortran-way)的顺序,您将有两个选择。以下是np.reshapenp.transposenp.array_split -

的实施
def split_submatrix(x,submat_shape,order='C'):
    p,q = submat_shape      # Store submatrix shape
    m,n = x.shape

    if np.any(np.mod(x.shape,np.array(submat_shape))!=0):
        raise Exception('Input array shape is not divisible by submatrix shape!')

    if order == 'C':
        x4D = x.reshape(-1,p,n/q,q).transpose(0,2,1,3).reshape(-1,p,q)
        return np.array_split(x4D,x.size/(p*q),axis=0)

    elif order == 'F':
        x2D = x.reshape(-1,n/q,q).transpose(1,0,2).reshape(-1,q)
        return np.array_split(x2D,x.size/(p*q),axis=0)

    else:
        print "Invalid output order."
        return x

使用修改的样本输入运行样本 -

In [201]: x
Out[201]: 
array([[5, 2, 5, 6, 5, 6, 1, 5],
       [1, 1, 8, 4, 4, 5, 2, 5],
       [4, 1, 6, 5, 6, 4, 6, 1],
       [5, 3, 7, 0, 5, 8, 6, 5],
       [7, 7, 0, 6, 5, 2, 5, 4],
       [3, 4, 2, 5, 0, 7, 5, 0]])

In [202]: split_submatrix(x,(3,4))
Out[202]: 
[array([[[5, 2, 5, 6],
         [1, 1, 8, 4],
         [4, 1, 6, 5]]]), array([[[5, 6, 1, 5],
         [4, 5, 2, 5],
         [6, 4, 6, 1]]]), array([[[5, 3, 7, 0],
         [7, 7, 0, 6],
         [3, 4, 2, 5]]]), array([[[5, 8, 6, 5],
         [5, 2, 5, 4],
         [0, 7, 5, 0]]])]

In [203]: split_submatrix(x,(3,4),order='F')
Out[203]: 
[array([[5, 2, 5, 6],
        [1, 1, 8, 4],
        [4, 1, 6, 5]]), array([[5, 3, 7, 0],
        [7, 7, 0, 6],
        [3, 4, 2, 5]]), array([[5, 6, 1, 5],
        [4, 5, 2, 5],
        [6, 4, 6, 1]]), array([[5, 8, 6, 5],
        [5, 2, 5, 4],
        [0, 7, 5, 0]])]