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