In Julia, if t is some matrix
t = [1 2; 3 4]
t1 = t
t1[1,1] = 0
t2 = t
t2 gives out same output as t1.
How can I make t2 to equal t?
In Julia, if t is some matrix
t = [1 2; 3 4]
t1 = t
t1[1,1] = 0
t2 = t
t2 gives out same output as t1.
How can I make t2 to equal t?
They are all equal actually:
julia> t = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> t1 = t
2×2 Matrix{Int64}:
1 2
3 4
julia> t1[1,1] = 0
0
julia> t2 = t
2×2 Matrix{Int64}:
0 2
3 4
julia> t == t1 == t2
true
julia> t === t1 === t2
true
julia> pointer(t), pointer(t1), pointer(t2) # identical
(Ptr{Int64} @0x00007fd213d37000, Ptr{Int64} @0x00007fd213d37000, Ptr{Int64} @0x00007fd213d37000)
The variables t, t1, and t2 point to the same data, the same memory location. So when you mutate t1 you mutate all.
If you want them to be different, such that only one is modified, you have to use copy:
julia> t = [1 2; 3 4];
julia> t1 = copy(t);
julia> t1[1,1] = 0;
julia> t2 = copy(t); # or just t if you want to avoid the copy
julia> t == t1 == t2
false
julia> pointer(t), pointer(t1), pointer(t2)
(Ptr{Int64} @0x00007fd21220e900, Ptr{Int64} @0x00007fd2142f9630, Ptr{Int64} @0x00007fd2142f9a90)