Search code examples
vectorjulia

Julia: append to an empty vector


I would like to create an empty vector and append to it an array in Julia. How do I do that?

x = Vector{Float64}
append!(x, rand(10))

results in

`append!` has no method matching append!(::Type{Array{Float64,1}}, ::Array{Float64,1})

Thanks.


Solution

  • Your variable x does not contain an array but a type.

    x = Vector{Float64}
    typeof(x)  # DataType
    

    You can create an array as Array(Float64, n) (but beware, it is uninitialized: it contains arbitrary values) or zeros(Float64, n), where n is the desired size.

    Since Float64 is the default, we can leave it out. Your example becomes:

    x = zeros(0)
    append!( x, rand(10) )