#####Example 1################# a=rand(2,2) b=a b=ones(size(a)) a #####Example 2######################### a=rand(2,2) b=a b[1:4].=1.0 a
Q- Why do we get different results ? In example 1, “a” is not equal to “b”. But in example 2, “a” is equal to “b”.
My understanding was, in example 1 “a” should also change once we change “b” in step 3.
Your second assignment in Example 1 (b = ones(size(a))) means that b no longer refers to the same matrix that a does. In Example 2 on the other hand, you are changing the elements of the matrix that b refers to, which a also refers to.
b = ones(size(a))
b
a
you can use
b .= ones(size(a))
or
b[:] = ones(size(a))
to update the whole matrix a.
Or, more conveniently,
b .= 1.0
Both of your examples needlessly create and allocate an entire new matrix on the right hand side of the assignment.