Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized arrays in Julia

Tags:

arrays

julia

Say that I have an array of some composite type in Julia. I understand that I can't simply assign values into the array since its elements are undefined. For example the code

type struct
  u::Int64
  v::Int64
end

X = Array(struct, 100)
X[10].u = 3

will generate this error:

ERROR: access to undefined reference
 in getindex at array.jl:277
 in include at boot.jl:238
 in include_from_node1 at loading.jl:114

What is the standard way to deal with this? For now I am just doing something like:

samples = Array(Sample1d, num_samples)
fill!(samples, Sample1d(0, 0, 0))
samples[i] = ...

Is there a more concise or Julian way to do this?

like image 752
Arrigo Avatar asked Jun 25 '14 19:06

Arrigo


People also ask

How do you initialize an array in Julia?

An Array in Julia can be created with the use of a pre-defined keyword Array() or by simply writing array elements within square brackets([]). There are different ways of creating different types of arrays.

How do you create an empty array in Julia?

Empty Arrays To initialize an empty array, it is perfectly valid to use n = 0 in the above expressions.

How do you initialize a vector in Julia?

The easiest way to initialize them are probably list comprehensions, for example: julia> [[Vector{Float64}(undef, 4) for _ = 1:5] for _ = 1:6] 5-element Array{Array{Array{Float64,1},1},1}: ...

What is undef in Julia?

#undef simply stands for a reference that hasn't been specified yet. See the following example: julia> x = Vector{Int}(undef, 3) 3-element Vector{Int64}: 139777823454816 139777979780016 0 julia> y = Vector{String}(undef, 3) 3-element Vector{String}: #undef #undef #undef.


1 Answers

You can use fill to create and fill an array at the same time:

type struct
  u::Int
  v::Int
end

struct() = struct(0, 0)
X = fill(struct(), 100)
X[10].u = 3
like image 85
Mr Alpha Avatar answered Oct 04 '22 01:10

Mr Alpha