Filling non-contiguous slices of an array with the real and imaginary part of another

Hello,

I would like to get your feedback on the fastest way to fill the 1 modulo 3 entries with the real part of an array and the 2 modul0 3 entries with the imaginary part of the same array.

using BenchmarkTools
A = rand(ComplexF64, 20, 50)

B = zeros(20,150)
B[:,1:3:end-1] .= real(A)
B[:,2:3:end]   .= imag(A)

function test1(A)
B = zeros(20,150)
B[:,1:3:end-1] .= real(A)
B[:,2:3:end]   .= imag(A)
end

@btime test1($A)

9.327 μs (4 allocations: 39.39 KiB)

Did you try dotting the real and imag calls, i.e.

3 Likes

Don’t forget to broadcast the real and imag functions to avoid allocations.

1 Like

Thank you for your answers. Just for future reference:

function test2(A)
B = zeros(20,150)
    B[:,1:3:end-1] .= real.(A)
    B[:,2:3:end]   .= imag.(A)
end

@btime test2($A)

2.477 μs (2 allocations: 23.52 KiB)

2 Likes