I’m trying to do y = x[ind] in-place, where y, x, ind are all vectors. By in-place, I mean no memory is allocated. I’m able to achieve this using a hand-written for loop (assign2! below). I suspect there is a way to achieve this using broadcasting, which could potentially generate better code. However, I haven’t been able to find it. assign! below is my attempt at it. Is there a simple line of code using broadcasting that works (doesn’t allocate, & is fast)? Why doesn’t the @. find it?
using BenchmarkTools, Random
x = randn(100)
y = zeros(200)
ind = vcat(randperm(100), randperm(100))
assign!(y, x, ind) = @inbounds @. y = x[ind]
@btime assign!($y, $x, $ind);
function assign2!(y, x, ind)
@simd for i in eachindex(ind)
@inbounds y[i] = x[ind[i]]
end
end
@btime assign2!($y, $x, $ind);