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?
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.
Empty Arrays To initialize an empty array, it is perfectly valid to use n = 0 in the above expressions.
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}: ...
#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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With