pythonmatrixnumpysplitstrassen

How to split a matrix into 4 blocks using numpy?


I'm implementing Strassen's Matrix Multiplication using python. In divide step, we divide a larger matrix into smaller sub-matrices. Is there a built-in numpy function to split a matrix?


Solution

  • Not exactly, but using array slicing notation you should be able to do it yourself pretty easily.

    >>> A = np.linspace(0,24,25).reshape([5,5,])
    >>> A
    array([[  0.,   1.,   2.,   3.,   4.],
           [  5.,   6.,   7.,   8.,   9.],
           [ 10.,  11.,  12.,  13.,  14.],
           [ 15.,  16.,  17.,  18.,  19.],
           [ 20.,  21.,  22.,  23.,  24.]])
    

    Make B the top-left 2x2 in A:

    >>> B = A[0:2,0:2]
    

    Note that B is a view, it shares data with A

    >>> B[1,1] = 60
    >>> print A
    [[  0.   1.   2.   3.   4.]
     [  5.  60.   7.   8.   9.]
     [ 10.  11.  12.  13.  14.]
     [ 15.  16.  17.  18.  19.]
     [ 20.  21.  22.  23.  24.]]
    

    If you need to copy the data from A, use the copy method:

    >>> B = A[0:2,0:2].copy()
    >>> B
    array([[  0.,   1.],
           [  5.,  60.]])
    >>> B[1,1] = 600
    >>> B
    array([[   0.,    1.],
           [   5.,  600.]])
    >>> A
    array([[  0.,   1.,   2.,   3.,   4.],
           [  5.,  60.,   7.,   8.,   9.],
           [ 10.,  11.,  12.,  13.,  14.],
           [ 15.,  16.,  17.,  18.,  19.],
           [ 20.,  21.,  22.,  23.,  24.]])