Reputation: 172
I have the following two structs. When I initialize the struct with a constructor, an array is created, but it is not what I expected.
using Distributions
mutable struct XYZ
x::Float64
y::Float64
z::Float64
end
mutable struct Coords
r::Vector{XYZ}
end
""" Make a structure called test that contains a vector of type XYZ
I want to have 10 XYZ structs in the "r" Vector """
Coords() = ( rand(Uniform(0,1.0),10,3) )
test = Coords()
I want to access test
by going test.r.x[i]
, however Julia complains that type Tuple has no field r. What it does create is a 2 dimensional array of size 10x3 and I can call elements via test[i,j]
but this is far from what I want. I want to have other arrays/variables in the composite with callable names...
I tried initializing this way as well
XYZ() = (rand(),rand(),rand())
Coords() = ([ XYZ() for i in 1:10 ])
test = Coords()
I still get the same warning. It seems like I have created a tuple rather than a composite type. How do I create a composite type that has arrays/vectors inside of other structs?
I am using Julia version 1.0.2
Upvotes: 1
Views: 218
Reputation: 20950
Your are never actually calling the inner constructor in Coords()
. To achieve what you want:
XYZ() = XYZ(rand(), rand(), rand())
Coords() = Coords([XYZ() for _ in 1:10])
But I would recommend against providing a constructor that initializes a special random layout. Instead, you could properly overload rand
for XYZ
, which gives you an array-rand
for free:
julia> import Random
julia> Random.rand(rng::Random.AbstractRNG, ::Random.SamplerType{XYZ}) = XYZ(rand(rng), rand(rng), rand(rng))
julia> rand(XYZ)
XYZ(0.7580070440261963, 0.15662533181464178, 0.7450476071687568)
julia> rand(XYZ, 10)
10-element Array{XYZ,1}:
XYZ(0.5984858021544213, 0.16235318543392796, 0.729919026616209)
XYZ(0.45516751074248374, 0.9667694185826785, 0.39798147467761247)
XYZ(0.7329129925610325, 0.7725520616259764, 0.42264014343531)
XYZ(0.10415869248789567, 0.4193162272272648, 0.3265074454289505)
XYZ(0.2286383169588948, 0.7119393337105202, 0.5166340562764509)
XYZ(0.23011692279595186, 0.35344093654843767, 0.9488399720160021)
XYZ(0.20464532213275577, 0.05761320898130973, 0.7694525743407523)
XYZ(0.3022492318001946, 0.9212313012991236, 0.819167833632835)
XYZ(0.6331585756351794, 0.9812979781832118, 0.3969247687412505)
XYZ(0.6049257667248391, 0.7155977104637223, 0.5294492917395452)
julia> Coords(rand(XYZ, 10))
Coords(XYZ[XYZ(0.633945, 0.882152, 0.750866), XYZ(0.496134, 0.241877, 0.188791), XYZ(0.267383, 0.552298, 0.613393), XYZ(0.569428, 0.503757, 0.120985), XYZ(0.822557, 0.982106, 0.37321), XYZ(0.250684, 0.701853, 0.509496), XYZ(0.886511, 0.83301, 0.381657), XYZ(0.628089, 0.00574949, 0.730268), XYZ(0.382186, 0.411701, 0.86016), XYZ(0.904469, 0.854098, 0.270464)])
Upvotes: 3