Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Vector of Length n in Julia

Tags:

julia

I want to create a vector/array of length n to be filled afterwards.

How can I do that? And does it have to be filled already with something?

like image 668
Georgery Avatar asked Apr 11 '20 16:04

Georgery


1 Answers

For example if you want a Vector of Ints of length 10 you can write

v = Vector{Int}(undef, 10)

And more general for an Array of Ints of dimensions (2, 3, 4)

a = Array{Int}(undef, (2, 3, 4))

Note that this fills the Vector/Array with garbage values, so this can be a bit dangerous. As an alternative you can use

v = Vector{Int}()
sizehint!(v, 10)
push!(v, 1) # add a one to the end of the Vector
append!(v, (2, 3, 4, 5, 6, 7, 8, 9, 10)) # add values 2 to 9 to the end of the vector

sizehint! is not necessary, but it can improve performance, because it tells Julia to expect 10 values.

There are other functions such as zeros, ones or fill that can provide a Vector/Array with already filled in data.

like image 99
Simon Schoelly Avatar answered Nov 10 '22 12:11

Simon Schoelly