在Julia

时间:2019-01-22 08:17:43

标签: arrays julia

我有以下两个结构。当我使用构造函数初始化结构时,会创建一个数组,但这不是我期望的。

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

我想通过进入test来访问test.r.x[i],但是Julia抱怨说Tuple类型没有字段r。它确实创建了一个尺寸为10x3的二维数组,我可以通过test[i,j]来调用元素,但这远非我想要的。我想在组合中包含其他具有可调用名称的数组/变量...

我也尝试过这种初始化方式

XYZ() = (rand(),rand(),rand())
Coords() = ([ XYZ() for i in 1:10 ])
test = Coords()

我仍然收到相同的警告。好像我创建了一个元组而不是复合类型。如何创建在其他结构内部具有数组/向量的复合类型?

我正在使用Julia版本1.0.2

1 个答案:

答案 0 :(得分:2)

您实际上从未真正在Coords()中呼叫inner constructor。实现您想要的:

XYZ() = XYZ(rand(), rand(), rand())
Coords() = Coords([XYZ() for _ in 1:10])

但是我建议不要提供初始化特殊随机布局的构造函数。相反,您可以适当地overload randXYZ,这将为您免费提供一个数组-rand

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