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?
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.
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.
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 .
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With