Matrix values

I am working with a code that first defines a matrix and then changes some values of that matrix.

For example:
temp1 = zeros(5,5);
temp2 = temp1;
temp2[[1; 3]] = [4; 3];

I would expect that the values of matrix temp1 would remain unchanged. But somehow the values of matrix temp1 are the same as the values of matrix temp2 at the end of the code.

temp1
5×5 Array{Float64,2}:
4.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
3.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0

temp2
5×5 Array{Float64,2}:
4.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
3.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0

This behavior seems odd to me. Why is Julia doing this? Can somebody help me with this point?

Many thanks in advance.

If you don’t want this behavior, temp2.=temp1 will make a copy.

1 Like

As Oscar says, temp2 = temp1 just creates a new variable temp2 that is a different name for temp1, not a new underlying object. Consider:

julia> t1 = zeros(5, 5);

julia> t2 = t1;

julia> t2 === t1
true

help?> ===
search: === == !==

  ===(x,y) -> Bool
  ≡(x,y) -> Bool

  Determine whether x and y are identical, in the sense that no program could distinguish them. First the types of x and y are compared. If those are identical, mutable objects are compared by address in
  memory and immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes called "egal". It always returns a Bool value.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> a = [1, 2]; b = [1, 2];
  
  julia> a == b
  true
  
  julia> a === b
  false
  
  julia> a === a
  true

Here’s a helpful blogpost that explains some of this: Values vs. Bindings: The Map is Not the Territory | juliabloggers.com

2 Likes

Many thanks, Oscar! temp2.=temp1 gave me an error, but temp2=copy(temp1) worked.

Understood perfectly now. Many thanks! I have to go over the code from the beginning to see if there are more instances like this. This reasoning is different from Matlab and it was unexpected to me. Thank you once again.

If you’re coming from MATLAB it might be useful to look at: Noteworthy Differences from other Languages · The Julia Language

Incidentally, the topic of this thread is point 2 on the list :slight_smile:

4 Likes

Many, many thanks, Nils!! It will be a great help. Thank you once again.

I am late, but I will shamelessly promote my post trying to build a simple mental model of why you should see Julia “variables” as labels, not boxes.

2 Likes

Many thanks, Henrique! Vem muito a tempo :slight_smile:

1 Like

XD, bom saber.