Copy or view, issue

Following Noteworthy Differences from other Languages · The Julia Language which says that:

Julia arrays are not copied when assigned to another variable. After A = B, changing elements of B will modify A as well. To avoid this, use A = copy(B).

I expected the following code to overwrite A. However this doesn’t happen:

using Random

function myfun()
    
    Random.seed!(1)
    A = Int8[0 1; 1 0]
    display(A)
    print("\n")

    block_A = A

    for i = 2:3
        display(block_A)
        block_A = rand(Int8, i,i)
    end
    display(block_A)
    print("\n")

    display(A)
end

myfun()
1 Like

What’s happening is that in the loop, the line:

block_A = rand(Int8, i, i)

is reassigning what block_A refers to, rather than altering it. So A is not affected. If you do something like:

for i = 2:2
        display(B)
        print("\n")
        B .= rand(Int8, i, i)
    end

where you use .= to reassign each element this has the expected effect.

5 Likes