Junwei su
Junwei su

Reputation: 138

How to declare a vector of vector in Julia

I want to declare a vector of vector in Julia like the following

V = [v1, v2, v3,...] where v1, v2, v3... have dimension of K x 1

What is the syntax to achieve this?

Upvotes: 3

Views: 10066

Answers (2)

spacetyper
spacetyper

Reputation: 1601

In Julia 1.0+ the accepted answer no longer works.

Now you must do something like:

V = [Vector{Float64}(undef,5) for _ in 1:10]

Upvotes: 10

DNF
DNF

Reputation: 12644

You can use Vector{Vector{Float64}}(5)to declare a length-5 vector of floating point vectors, for example, or Vector{Vector{Float64}}(0)for an empty one. But this doesn't really allocate memory, since the size of each contained vector is undefined.

If you want to actually allocate memory, you can use a comprehension like this:

V = [Vector{Float64}(5) for _ in 1:10]

for a length 10 vector of length 5 vectors. If you want to initialize to zero, do

V = [zeros(5) for _ in 1:10]

Upvotes: 6

Related Questions