0

I've encountered something curious with array variables. Suppose I create

A=[1. 2;3 4] and then define B=A. If I then set A[1,1]=7, the [1,1] entry in B changes. But if I set A=ones(2,2), the entries in B do not change.

Any comments?

carstenbauer
  • 9,817
  • 1
  • 27
  • 40
Jeff
  • 3
  • 2
  • Possible duplicate of [Creating copies in Julia with = operator](https://stackoverflow.com/questions/33002572/creating-copies-in-julia-with-operator) – Gnimuc Apr 18 '18 at 10:22

1 Answers1

1

B=A assigns A to B and does not create a copy. Therefore A and B both point to the same piece of memory. Changing something in B will inevitably also alter A and vice versa. A and B are identical, to be checked with A === B (note the three equal signs).

You can create a copy of A by C = copy(A). Note that in this case A == C but A !== C, i.e. they have the same entries but aren't identical.

A = ones(2,2) allocates a new 2x2 array and fills it with ones (ones(2,2)) and afterwards assigns this array to A (A = ...). Therefore any connection to B is lost. Note that if you would do A .= ones(2,2) (note the dot before the equal sign which indicates in-place assignment) you would also alter B.

carstenbauer
  • 9,817
  • 1
  • 27
  • 40
  • @Jeff Also note that if your array has array elements, eg `[[1,2],[3,4]]`, then you would need to use `deepcopy` to get a truly independent variable, since `copy` only creates new values at the first level of nesting. – Colin T Bowers Apr 17 '18 at 23:14