# Allocation with Subset of Matrix and Views

**URL:** <https://discourse.julialang.org/t/allocation-with-subset-of-matrix-and-views/82998>\
**Category:** General Usage\
**Tags:** memory-allocation\
**Created:** [June 19, 2022, 3:30am UTC](https://discourse.julialang.org/t/allocation-with-subset-of-matrix-and-views/82998 "2022-06-19T03:30:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![TI36XPro](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ti36xpro/32/33658_2.png) [@TI36XPro](https://discourse.julialang.org/u/TI36XPro)\
**Post date:** [June 19, 2022, 3:30am UTC](https://discourse.julialang.org/t/allocation-with-subset-of-matrix-and-views/82998/1 "2022-06-19T03:30:51Z")

</div>

Hello,

I’m wondering if anyone can help me understand the following. I want to replace a subset of matrix `A` with matrix `B`. I understand this can be done efficiently using `for` loops or `copyto!`. I am specifically interested in the behavior of the following case.

The following does not allocate.

```julia
A = zeros(5, 5)
B = ones(3, 3) * 2
function viewtest!(A, B)
    tmp = @view A[2:4, 2:4]
    tmp .= B
    return nothing
end
@allocated viewtest!(A, B) # 0

```

This function does allocate.

```julia
function broadcasttest!(A, B)
    A[2:4, 2:4] .= B
end
@allocated broadcasttest!(A, B) # 64

```

I think in `broadcasttest!` the code `A[2:4, 2:4]` means I am creating a slice of an array which is going to allocate? Is that why? My initial expectation was this would also have zero allocation because it is an inplace operation (I think) reflected by the `.=`

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [June 20, 2022, 3:20pm UTC](https://discourse.julialang.org/t/allocation-with-subset-of-matrix-and-views/82998/2 "2022-06-20T15:20:10Z")

</div>

EDIT: see the following post - there may not have been any deeper issue here.

There’s definitely something unfortunate happening here and it could probably be better. It’s an interaction of the left-hand slice and `.=`. But

```julia
function broadcasttest!(A, B)
    A[2:4, 2:4] = B # not .=
end
@allocated broadcasttest!(A, B) # 0

```

does what you want if you don’t need the broadcasting to expand singleton dimensions.

---

<div class="post-metadata">

**Author:** ![TI36XPro](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ti36xpro/32/33658_2.png) [@TI36XPro](https://discourse.julialang.org/u/TI36XPro)\
**Post date:** [June 20, 2022, 4:04pm UTC](https://discourse.julialang.org/t/allocation-with-subset-of-matrix-and-views/82998/3 "2022-06-20T16:04:31Z")

</div>

Actually I think I did something stupid here. `return nothing` was missing from `broadcasttest!`
