Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的块矩阵赋值_Python_Numpy_Matrix - Fatal编程技术网

Python中的块矩阵赋值

Python中的块矩阵赋值,python,numpy,matrix,Python,Numpy,Matrix,根据本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.],

根据本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的值保持为零。如果分两步执行类似操作,则一切正常:

>>> 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]
不是数组的视图,而是一个单独的副本-

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

为了解决这个问题,我们可以使用-

验证结果-

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

太神了谢谢。为什么这是副本而不是视图?以下是一些相关的解释:
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.]])