Avoiding allocations in small subvector ops

In the code below, there is an allocation each time the statement u[i1:i1+1].=... is executed. A few years ago, I wrote a quick-and-dirty macro to implement statements like this with a for-loop like the commented-out loop in the code below. I suppose now there is a standard macro that implements the statement with a for-loop. Or maybe there is a better way to use dot-notation to avoid the allocation.

function many_vector_adds(n,ncopy)
    u = zeros(n)
    for i = 1 : n
        u[i] = i
    end
    for i = 1 : ncopy
        i1 = Int(floor(sin(i)^2 * (n - 1))) + 1
        i2 = Int(floor(cos(i)^2 * (n - 1))) + 1
        u[i1 : i1 + 1] .= u[i1 : i1 + 1] ./ 2 .+ u[i2 : i2 + 1]        
        #for j = 0 : 1
        #    u[i1 + j] = u[i1 + j] / 2 + u[i2 + j]
        #end

    end
    u[100]
end
@time many_vector_adds(10_000, 1_000_000)

I think what allocates there are the slices on the right side.

2 Likes

Thanks, that worked!