How to split matrix into 4 blocks using numpy?

I am doing Strassen matrix multiplication using python. At the step of division, we divide the large matrix into smaller submatrices. Is there a numpy built-in function for partitioning a matrix?

+6
source share
2 answers

Not really, but using array notation notation you can easily do it yourself.

>>> 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 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 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.]]) 
+11
source

I ran into the same problem and found some numpy built-in functions to split my matrix into 4 submatrices (my matrices are 2 ^ N * 2 ^ N in size)

Here is the code I wrote:

 upper_half = np.hsplit(np.vsplit(my_matrix, 2)[0], 2) lower_half = np.hsplit(np.vsplit(my_matrix, 2)[1], 2) upper_left = upper_half[0] upper_right = upper_half[1] lower_left = lower_half[0] lower_right = lower_half[1] 

Bonus for recombining them with numpy:

 C=np.vstack([np.hstack([c11, c12]), np.hstack([c21, c22])]) 

vsplit hsplit hstack and vstack seem to be made for this purpose

+2
source

Source: https://habr.com/ru/post/918497/


All Articles