Nick Nick Nick
Nick Nick Nick

Reputation: 189

Why NumPy: np.fill_diagonal() changes the diagnoal values of all related variables?

Dear experienced friends, I met a question when I was trying to use the np.fill_diagonal(). Firstly I set two sub-variables from an original NumPy array. Then I used np.fill_diagonal() to change the diagonal values of one of the variables. However, I found all variables' diagonal values have been changed.

May I ask why this happened? Are all the related NumPy variables share the same memory? And how can I know their exact memory relationship? Thank you!

Here is the simple code:

# we set the original one
a = np.array([[    10., 1., 1., 1.,  1.],
        [2.,  20., 140.,  8.,   57.],
        [3.,  3.,  30.,   21.,  51.],
        [4.,  4.,  21.,   40.,  56.],
        [5.,  5.,  31.,  16.,   50.]])

# the two sub-variables
b1 = a[:5,:5]
b2 = a[:5,:5]

# then I change the diagonal value of one of the sub-variables
np.fill_diagonal(b1, 0)

We are supposed to only change the value of b1, but actually all a, b1, and b2 are changed. May I ask how can I change the diagonal value of b1 only but not affect others? Thank you!

a

array([[  0.,   1.,   1.,   1.,   1.],
       [  2.,   0., 140.,   8.,  57.],
       [  3.,   3.,   0.,  21.,  51.],
       [  4.,   4.,  21.,   0.,  56.],
       [  5.,   5.,  31.,  16.,   0.]])

b2

array([[  0.,   1.,   1.,   1.,   1.],
       [  2.,   0., 140.,   8.,  57.],
       [  3.,   3.,   0.,  21.,  51.],
       [  4.,   4.,  21.,   0.,  56.],
       [  5.,   5.,  31.,  16.,   0.]])

Upvotes: 1

Views: 115

Answers (1)

Hmkyriacou
Hmkyriacou

Reputation: 74

It looks like b1 and b2 are just references to a. Try using numpy.copy() and then preforming the splicing to get a "deep copy" so that b1 and b2 have their own spaces in memory. check out numpy.copy in the Numpy API documentation.

Upvotes: 1

Related Questions