Is there a simple way to map a vector to multiple vectors?
vin = [1,2,3,4]
v1, v2, v3 = map(v) do x
return x, 2x, 3x
end
The above doesn’t work, but that shows what I mean. Usually, you’d get a vector of tuples from the above, but is there an idiomatic way to get arrays directly instead?
I know that I could do something like:
vin = [1,2,3,4]
v1 = Vector{Int}(undef, length(vin))
v2 = Vector{Int}(undef, length(vin))
v3 = Vector{Int}(undef, length(vin))
for i in eachindex(vin)
v1[i] = x
v2[i] = 2x
v3[i] = 3x
end
so I’m asking if there is an existing more concise way.
Note: I would prefer a solution that is at least as performant as that. For example, doing 3 separate map/broadcasts which seems to be about 25% slower for large arrays (which is what I’m working with).
Performance test for 3 approaches
div2(x) = x / 2
times2(x) = 2*x
times3(x) = 3*x
function test1(v)
return map(div2, v), map(times2, v), map(times3, v)
end
function test2(v)
return div2.(v), times2.(v), times3.(v)
end
function test3(v)
len = length(v)
v1 = Vector{Float64}(undef, len)
v2 = Vector{Int}(undef, len)
v3 = Vector{Int}(undef, len)
@inbounds for i in eachindex(v)
x = v[i]
v1[i] = div2(x)
v2[i] = times2(x)
v3[i] = times3(x)
end
return v1, v2, v3
end
using BenchmarkTools
function time3(n=100000)
v = fill(17, n)
@btime test1($v)
@btime test2($v)
@btime test3($v)
return
end