For example, suppose that we have an array type such as Atype = Array{ComplexF64,3}
and would like to create an array of the same container type (in this case Array
) but with a different element type, say Int
(so the target array type is Array{Int,K}
for some dimension K
). The size of the array to create is known. What is the most compact (and least allocating) way to achieve this?
If an instance of Atype
already exists, we can use similar
:
Atype = Array{ComplexF64,3}
a = Atype(undef, (10,10,10)) # size of existing array is (10,10,10)
sz = (3,4) # size of target array is (3,4)
b = similar(a, Int, sz)
However, I don’t have an existing a::Atype
and do not want to create such a
. The best I have so far is something like
Atype = Array{ComplexF64,3}
sz = (3,4)
b = similar(Atype(undef, (0,0,0)), Int, sz)
but Atype(undef, (0,0,0))
is still allocating (though very small), and when the dimension of the array is parametrized, the method becomes a bit convoluted:
K = 3 # parametrized dimension
Atype = Array{ComplexF64,K}
sz = (3,4)
b = similar(Atype(undef, ntuple(k->0,Val(K))), Int, sz)
I wished I had something like
K = 3
Atype = Array{ComplexF64,K}
sz = (3,4)
b = similar(Atype, Int, sz)
but this does not work.
Is there a better way than shown above?