logo

How to Create an Empty Array in Julia 📂Julia

How to Create an Empty Array in Julia

Code

Size Specification

julia> empty = Array{Float64, 2}(undef, 3, 4)
3×4 Array{Float64,2}:
 3.39519e-313  3.18299e-313  4.66839e-313  1.061e-313
 4.03179e-313  5.51719e-313  1.6976e-313   4.24399e-314
 2.97079e-313  4.66839e-313  7.00259e-313  5.0e-324

Executing the code above results in an empty array being created. Occasionally, it may seem like a strange value such as 1.76297e-315 is entered, but this is a value very close to 0, so it’s not a major issue for initialization.

Array{X, Y}(undef, ...) creates an array of size ... filled with uninitialized values of data type X and dimension Y. The key here is undef.

Resizable Arrays

In the case of a one-dimensional array, an empty array can be simply made by not putting anything inside the parentheses.

julia> empty = Array{Float64, 1}()
Float64[]

julia> empty = Array{Float64, 2}()
ERROR: MethodError: no method matching Array{Float64,2}()
Closest candidates are:
  Array{Float64,2}(::UndefInitializer, ::Int64, ::Int64) where T at boot.jl:408
  Array{Float64,2}(::UndefInitializer, ::Int64...) where {T, N} at boot.jl:412
  Array{Float64,2}(::UndefInitializer, ::Tuple{Int64,Int64}) where T at boot.jl:416
  ...
Stacktrace:
 [1] top-level scope at REPL[85]:1

However, trying to do the same for a two-dimensional array will result in a MethodError as shown above. Of course, it’s possible to create an empty array by making an array of one-dimensional arrays, but from a speed perspective, it is recommended to use the native syntax as it is.

julia> empty = Array{Array{Float64, 1}, 1}()
Array{Float64,1}[]

A Simpler Method

Using curly braces like below makes creating arrays even more straightforward.

julia> empty = Float64[]
Float64[]

julia> empty = Array{Float64, 1}[]
Array{Float64,1}[]

julia> empty = Array{Float64, 2}[]
Array{Float64,2}[]

Environment

  • OS: Windows
  • julia: v1.5.0