Julia: append to an empty vector

ID : 131390

viewed : 10

Tags : vectorjuliavector

Top 5 Answer for Julia: append to an empty vector

vote vote

96

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) ) 
vote vote

84

I am somewhat new to Julia and came across this question after getting a similar error. To answer the original question for Julia version 1.2.0, all that is missing are ():

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

This solution (unlike x=zeros(0)) works for other data types, too. For example, to create an empty vector to store dictionaries use:

d = Vector{Dict}() push!(d, Dict("a"=>1, "b"=>2)) 

A note regarding use of push! and append!:

According to the Julia help, push! is used to add individual items to a collection, while append! adds an collection of items to a collection. So, the following pieces of code create the same array:

Push individual items:

a = Vector{Float64}() push!(a, 1.0) push!(a, 2.0) 

Append items contained in an array:

a = Vector{Float64}() append!(a, [1.0, 2.0]) 
vote vote

71

You can initialize an empty Vector of any type by typing the type in front of []. Like:

Float64[] # Returns what you want Array{Float64, 2}[] # Vector of Array{Float64,2} Any[] # Can contain anything 
vote vote

60

New answer, for Julia 1. append! is deprecated, you now need to use push!(array, element) to add elements to an array

my_stuff = zeros() push!(my_stuff, "new element") 
vote vote

54

Top 3 video Explaining Julia: append to an empty vector

Related QUESTION?