Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: append to an empty vector

Tags:

vector

julia

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.

like image 370
Anarcho-Chossid Avatar asked Feb 15 '15 08:02

Anarcho-Chossid


People also ask

How do I append to an array in Julia?

Julia allows adding new elements in an array with the use of push! command. Elements in an array can also be added at a specific index by passing the range of index values in the splice! function.

What is the difference between push and append?

"Appending" adds to the end of a list, "pushing" adds to the front.

How do you define a vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do you create a matrix in Julia?

Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).


Video Answer


2 Answers

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) ) 
like image 58
Vincent Zoonekynd Avatar answered Sep 30 '22 21:09

Vincent Zoonekynd


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]) 
like image 21
japamat Avatar answered Sep 30 '22 23:09

japamat