Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array of `nothing` of any size in Julia

Tags:

julia

In Julia it is possible to create arrays of any size using the functions zeros(.) or ones(.). Is there a similar function to create an array that is filled with nothing at initialization but also accepts floats? I mean a function like in this example:

a = array_of_nothing(3)
# a = [nothing,nothing,nothing]
a[1] = 3.14
# a = [3.14,nothing,nothing]

I tried to find information on internet, but without success... Sorry, I am a beginner in Julia.

like image 904
Romain F Avatar asked Jan 28 '20 10:01

Romain F


2 Answers

The fill function can be used to create arrays of arbitrary values, but it's not so easy to use here, since you want a Vector{Union{Float64, Nothing}}. Two options come to mind:

A comprehension:

a = Union{Float64, Nothing}[nothing for _ in 1:3];
a[2] = 3.14;

>> a
3-element Array{Union{Nothing, Float64},1}:
  nothing
 3.14    
  nothing

Or ordinary array initialization:

a = Vector{Union{Float64, Nothing}}(undef, 3)
fill!(a, nothing)
a[2] = 3.14

It seems that when you do Vector{Union{Float64, Nothing}}(undef, 3) the vector automatically contains nothing, but I wouldn't rely on that, so fill! may be necessary.

like image 90
DNF Avatar answered Nov 01 '22 10:11

DNF


I think you are looking for the Base.fill — Function.

fill(x, dims)

This creates an array filled with value x.

println(fill("nothing", (1,3)))

You can also pass a function Foo() like fill(Foo(), dims) which will return an array filled with the result of evaluating Foo() once.

like image 8
Vivz Avatar answered Nov 01 '22 10:11

Vivz