Python中的块矩阵分配 [英] block matrix assignment in Python

查看:278
本文介绍了Python中的块矩阵分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过此mwe:

a=np.zeros((5,5))
b=np.zeros((2,2))
a=np.matrix(a)
b=np.matrix(b)
b[0,0]=4
b[1,1]=9
b[0,1]=7
indice=[2,3]
# 1
c=a[indice,:][:,indice]
c=b
print c
# 2
a[indice,:][:,indice]=b
print a[indice,:][:,indice]

我得到:

>>> c
matrix([[ 4.,  7.],
        [ 0.,  9.]])

和:

>>> a[indice,:][:,indice]
matrix([[ 0.,  0.],
        [ 0.,  0.]])

我不明白为什么 a 的值保持为零.如果分两步完成类似的操作,则一切正常:

I do not understand why the values of a remain zeroes. If a similar operation is done in two steps, everything works fine:

>>> for k in range(len(indice)):
...     a[indice[k],indice]=b[k,:]

我获得:

>>> a
matrix([[ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  4.,  0.,  7.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  9.,  0.],
        [ 0.,  0.,  0.,  0.,  0.]])

推荐答案

这是因为a[indice,:][:,indice]不是数组的视图,而是单独的副本-

It's because a[indice,:][:,indice] isn't a view into the array but is a separate copy -

In [142]: np.may_share_memory(a, a[indice,:][:,indice])
Out[142]: False


要解决此问题,我们可以使用 np.ix_ -


To solve it, we can use np.ix_ -

a[np.ix_(indice, indice)] = b

验证结果-

In [145]: a
Out[145]: 
matrix([[ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.]])

In [146]: b
Out[146]: 
matrix([[ 4.,  7.],
        [ 0.,  9.]])

In [147]: a[np.ix_(indice, indice)] = b

In [148]: a
Out[148]: 
matrix([[ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  4.,  7.,  0.],
        [ 0.,  0.,  0.,  9.,  0.],
        [ 0.,  0.,  0.,  0.,  0.]])

In [149]: a[indice,:][:,indice]
Out[149]: 
matrix([[ 4.,  7.],
        [ 0.,  9.]])

这篇关于Python中的块矩阵分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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