-1

I want to create two matrices. Then make the second matrix numbers changed depending on the numbers in the first matrix. So I generate an If statement about my first matrix and if true this will induce a change in my second matrix. However, it induces a change in both matrices?

My code works perfectly with single digit objects. It only occurs when I try to apply it with matrices.

import numpy as np
n = 3
matr = np.zeros((n,n))
matr[0][0] = 1
matr2 = matr

print(matr)
[[1. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

print(matr2)
[[1. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

if matr[0][0] == 1:
    matr2[0][0] = 9

print(matr)
[[9. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

print(matr2)
[[9. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Because "matr" doesn't occur as a subject in my if statement it shouldn't be altered right?

x = 1
y = x

if x == 1:
    y = 9

print(x)
1
print(y)
9

1 Answers1

0

Those 2 variables are just two references to the same matrix, not 2 different matrices; matr2 = matr just creates a new reference to the same matrix.

The statement matr2[0][0] = 9 modifies the one and only matrix that exists in your example, and it is exactly the same as using matr[0][0] = 9.

Ralf
  • 16,086
  • 4
  • 44
  • 68