How to initialize an empty 2-dimensional array in Julia?
Asked Answered
A

3

29
m = []

initializes an empty array of dimension 1. I want to initialize an empty array of dimension 2 (to which I'll append values later on). Is this possible?

Alida answered 1/2, 2016 at 8:50 Comment(0)
M
4

As of Julia 1.8

It's now much simpler to create empty arrays:

Empty n-dimensional arrays can now be created using multiple semicolons inside square brackets.

julia> m = [;;]
# 0×0 Matrix{Any}
julia> m = [;;;]
# 0×0×0 Array{Any, 3}

Note that this is just syntactic sugar for constructing an uninitialized Array:

julia/test/syntax.jl#L3143-L3146

@test []    == Array{Any}(undef, 0)
@test [;]   == Array{Any}(undef, 0)
@test [;;]  == Array{Any}(undef, 0, 0)
@test [;;;] == Array{Any}(undef, 0, 0, 0)
Mahogany answered 4/1, 2023 at 6:21 Comment(1)
This creates a 0x2 Matrix. But when assigning values to lets say the first column by gogo=Array{Any}(undef,0,2) : gogo[:,1]=go with go=ones(6) doesn't seem to work.Endamoeba
G
34

As of Julia 1.0 you can use:

m = Array{Float64}(undef, 0, 0)

for an (0,0)-size 2-D Matrix storing Float64 values and more in general:

m = Array{T}(undef, a, b, ...,z)

for an (a,b,...,z)-size multidimensional Tensor (whose content is garbage of type T).

Garneau answered 16/8, 2018 at 15:5 Comment(1)
I suggest you replace the T by Float64 in your examples. Otherwise people might copy past and get an error.Violate
E
15

Try:

m = reshape([],0,2)

or,

m = Array{Float64}(undef, 0, 2)

The second option which explicitly defines type should generate faster code.

A commenter ephemerally suggested using Matrix() for a 0x0 matrix and Matrix(0,2) for a 0x2 matrix.

Entomo answered 1/2, 2016 at 9:5 Comment(3)
I though that syntax was deprecated and instead one should use m = Array{Float64, 2}().Pelargonium
All variants seem to work warning-less in both 0.4 and 0.5. But, answer can changed to reflect better practice. Any reference?Entomo
The second one won't work on 1.0 anymore! You should really mention this in your answer. Also, you are missing the suggested way of doing it in 1.0 (see Antonello's answer).Violate
M
4

As of Julia 1.8

It's now much simpler to create empty arrays:

Empty n-dimensional arrays can now be created using multiple semicolons inside square brackets.

julia> m = [;;]
# 0×0 Matrix{Any}
julia> m = [;;;]
# 0×0×0 Array{Any, 3}

Note that this is just syntactic sugar for constructing an uninitialized Array:

julia/test/syntax.jl#L3143-L3146

@test []    == Array{Any}(undef, 0)
@test [;]   == Array{Any}(undef, 0)
@test [;;]  == Array{Any}(undef, 0, 0)
@test [;;;] == Array{Any}(undef, 0, 0, 0)
Mahogany answered 4/1, 2023 at 6:21 Comment(1)
This creates a 0x2 Matrix. But when assigning values to lets say the first column by gogo=Array{Any}(undef,0,2) : gogo[:,1]=go with go=ones(6) doesn't seem to work.Endamoeba

© 2022 - 2024 — McMap. All rights reserved.