Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
shobhu Avatar asked Jun 19 '12 16:06

shobhu


People also ask

How do you split an array in NumPy Python?

Splitting NumPy Arrays Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

How do I split a NumPy array vertically?

NumPy: vsplit() function The vsplit() function is used to split an array into multiple sub-arrays vertically (row-wise). Note: vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.

How do you split an array into parts in Python?

Use numpy. array_split() to split a list into n parts. Call numpy. array_split(list, n) to return a list of n NumPy arrays each containing approximately the same number of elements from list .


1 Answers

According to this answer, you might use the swapaxes:

You can create a helper method as:

def split(array, nrows, ncols):
    """Split a matrix into sub-matrices."""

    r, h = array.shape
    return (array.reshape(h//nrows, nrows, -1, ncols)
                 .swapaxes(1, 2)
                 .reshape(-1, nrows, ncols))

Here is an example of using it

import numpy as np

array = np.array([
    [1, 1, 2, 2],
    [3, 3, 4, 4],
    [5, 5, 6, 6],
    [7, 7, 8, 8]])

A, B, C, D =  split(array, 2, 2)
# A = 
# [[1 1]
#  [3 3]]

# B = 
# [[2 2]
#  [4 4]]

# C = 
# [[5 5]
#  [7 7]]

# D =
# [[6 6]
#  [8 8]]
print('A = \n{}\n\n'
      'B = \n{}\n\n'
      'C = \n{}\n\n'
      'D =\n{}'.format(A, B, C, D))
like image 179
Dat Avatar answered Sep 23 '22 07:09

Dat