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?

0

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I suggest you replace the T by Float64 in your examples. Otherwise people might copy past and get an error.
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.

3 Comments

I though that syntax was deprecated and instead one should use m = Array{Float64, 2}().
All variants seem to work warning-less in both 0.4 and 0.5. But, answer can changed to reflect better practice. Any reference?
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).
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)

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.