3

From this 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]

I get:

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

and:

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

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,:]

I obtain:

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

1 Answer 1

6

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

To solve it, we can use np.ix_ -

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

Verify result -

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.]])
Sign up to request clarification or add additional context in comments.

2 Comments

amazing ! Thank you.
Why is this a copy instead of a view? Here is some relevant explainations: scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.