0

I have a 'matrix', then choose one row as the 'vector', and then change one element in this vector. However, the element in the 'matrix' also changes. Why?

Matrix = [[1,2,3],[4,5,6],[7,8,9]]
Vector = Matrix[1]
print('Vector', Vector)
print('Matrix', Matrix)
Vector[1] = float(99)
print('Vector', Vector)
print('Matrix', Matrix)

Output:
Vector [4, 5, 6]
Matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Vector [4, 99.0, 6]
Matrix [[1, 2, 3], [4, 99.0, 6], [7, 8, 9]]
jpp
  • 159,742
  • 34
  • 281
  • 339
george s
  • 9
  • 1

3 Answers3

0

I assume this code is in Python. The reason this is happening is because Vector = Matrix[1] is assigning the reference of the 1-index row of Matrix to the variable Vector.

In order to get a deep copy of Matrix[1], use copy.deepcopy. Try the following code to see if the same assignment issue occurs:

import copy
Matrix = [[1,2,3],[4,5,6],[7,8,9]]
Vector = copy.deepcopy(Matrix[1])
Philip
  • 1
0

Python lists use pointers. The pointers for Vector and Matrix[1] in your code are the same. Try running the below code to see what I mean.

Matrix = [[1,2,3],[4,5,6],[7,8,9]]

Vector = Matrix[1]
print(id(Vector) == id(Matrix[1]))   # True

Vector2 = Matrix[1].copy()
print(id(Vector2) == id(Matrix[1]))  # False

See this answer for more details:

What exactly is the difference between shallow copy, deepcopy and normal assignment operation?

jpp
  • 159,742
  • 34
  • 281
  • 339
0

I can conclude that the assignment

Vector = Matrix[1]

Sets vector as reference to Matrix[1]

You'll need to make a copy of Matrix[1] instead.

If you are coding in Python i suggest u use deepcopy from copy package instead. Hope it helps