# Modifying elements of a Matrix

**URL:** <https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381>\
**Category:** New to Julia\
**Created:** [March 3, 2022, 10:51pm UTC](https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381 "2022-03-03T22:51:43Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kuldeep](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kuldeep/32/33657_2.png) [@Kuldeep](https://discourse.julialang.org/u/Kuldeep)\
**Post date:** [March 3, 2022, 10:51pm UTC](https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381/1 "2022-03-03T22:51:43Z")

</div>

```julia

#####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.

---

<div class="post-metadata">

**Author:** ![jkbest2](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jkbest2/32/7350_2.png) [@jkbest2](https://discourse.julialang.org/u/jkbest2)\
**Post date:** [March 3, 2022, 10:57pm UTC](https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381/2 "2022-03-03T22:57:32Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![photor](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/photor/32/14343_2.png) [@photor](https://discourse.julialang.org/u/photor)\
**Post date:** [March 4, 2022, 4:55am UTC](https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381/3 "2022-03-04T04:55:45Z")

</div>

you can use

```julia
b .= ones(size(a))

```

or

```julia
b[:] = ones(size(a))

```

to update the whole matrix a.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [March 4, 2022, 6:27am UTC](https://discourse.julialang.org/t/modifying-elements-of-a-matrix/77381/4 "2022-03-04T06:27:37Z")

</div>

Or, more conveniently,

```julia
b .= 1.0

```

Both of your examples needlessly create and allocate an entire new matrix on the right hand side of the assignment.
