如何使用numpy将矩阵拆分为4个块? [英] How to split a matrix into 4 blocks using numpy?

查看:1523
本文介绍了如何使用numpy将矩阵拆分为4个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python实现Strassen的矩阵乘法.在除法步骤中,我们将较大的矩阵划分为较小的子矩阵.是否有内置的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?

推荐答案

不完全是,但是使用数组切片表示法,您应该可以自己轻松地做到这一点.

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.]])

让B在A的左上角2x2:

Make B the top-left 2x2 in A:

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

请注意,B是一个视图,它与A共享数据

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.]]

如果您需要从A复制数据,请使用复制方法:

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.]])

这篇关于如何使用numpy将矩阵拆分为4个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆