The mutation function changes all the values in a dictionary

Hi everyone.
I am using a mutate function that changes the value of an array and then I save the array to a dictionary.
The problem is that the function changes all the values saved in the dictionary.

a = Dict()
b = ones(2,2)

function update_b!(b)
    b .= b .+1
end

for i in 1:2
    update_b!(b)
    a[i] = b
end

The result of a:

  2 => [3.0 3.0; 3.0 3.0]
  1 => [3.0 3.0; 3.0 3.0]

I would like something like:

  2 => [3.0 3.0; 3.0 3.0]
  1 => [2.0 2.0; 2.0 2.0]

Using the function with a return fixes the problem, but I would like to know if the problem can be fixed with a mutable function.

You are assigning the same object here to the left hand side. No copy is made implicitly. Changing b is thus reflected everywhere it is referenced.

Either assign a[i] = copy(b), or construct the dictionary like

a = Dict(i=>ones(2,2).+i for i in 1:2)
1 Like

Thank you very much, it worked perfectly.

Great! Then please mark my answer as the solution if you are happy with it and have no further questions, so others will know the topic needs no more immediate attention.