如何更改自定义类型数组元素中的特定字段?
问题描述:
这是交易。我取得了朱莉娅郎的自定义类型:如何更改自定义类型数组元素中的特定字段?
type points
x::Float64
y::Float64
z::Float64
end
而且也取得了这种类型的数组:
S = Array(ponits,1,Int(N))
所以现在我想改变我的(例如I = 3)数组元素的域x例如,4.28。但我这样做时:
S[3].x = 4.28
它改变ALL阵列S.因此我具有由具有的X日提交等于4.28的所有元素数组S。我读了朱莉娅的文件,并没有发现任何关于这个。它在Julia中如何工作?
在此先感谢。
P.S.哦,因为我已经做了这个线程。如何制作自定义类型的零元素?对于exaplme,零点类型将是类似(0,0,0)。
答
如果您有一个对同一对象的引用数组,并尝试对其中的一个进行变异,那么您将得到该结果,例如,如果使用fill()
功能,以填补对象的数组,可能导致以下问题:
julia> s=Vector{Points}(3)
3-element Array{Points,1}:
#undef
#undef
#undef
julia> fill!(s,Points(NaN,NaN,NaN))
3-element Array{Points,1}:
Points(NaN,NaN,NaN)
Points(NaN,NaN,NaN)
Points(NaN,NaN,NaN)
julia> s[1].x=1
1.0
julia> s
3-element Array{Points,1}:
Points(1.0,NaN,NaN)
Points(1.0,NaN,NaN)
Points(1.0,NaN,NaN)
为了避免这种问题的使用数组,理解来填补它:
s=[Points(NaN,NaN,NaN) for i=1:3]
但是我从您的示例代码看到的是:
Points
数据类型没有自定义constructor
并且此外,s
数组还没有初始化化的。
julia> s = Array(Points,1,4)
1x4 Array{points,2}:
#undef #undef #undef #undef
所以如果你尝试变异元素上,你会得到一个错误:
最小的变化julia> s[1].x
ERROR: UndefRefError: access to undefined reference
in getindex at array.jl:282
一个解决方案是使用Points
默认构造函数是这样的:
s[1]=Points(NaN,NaN,NaN)
后您将能够变异s
,s[1].x=4.28
其次具有Points
类型的zero
,应添加zero(::Points)
方法:
julia> import Base.zero
julia> zero(::Points)=Points(0,0,0)
zero (generic function with 14 methods)
julia> zero(Points(1,2,3))
Points(0.0,0.0,0.0)
提示:使用1XN阵列来处理N个元素的Array
是不是最好的选择,Refer,使用Vector{Type}(N)
代替。