Gic*_*kle 0 arrays types julia
这是交易.我在Julia lang做了一个自定义类型:
type points
x::Float64
y::Float64
z::Float64
end
Run Code Online (Sandbox Code Playgroud)
并且还制作了这种类型的数组:
S = Array(ponits,1,Int(N))
Run Code Online (Sandbox Code Playgroud)
所以现在我想将i的(例如i = 3)数组元素的字段x改为例如4.28.但是当我这样做时:
S[3].x = 4.28
Run Code Online (Sandbox Code Playgroud)
它改变了所有数组S.因此,我有阵列S,其中所有元素的x-filed等于4.28.我阅读了朱莉娅的文件,但没有找到任何相关信息.它在Julia中如何运作?
提前致谢.
PS哦,因为我已经做了这个帖子.如何制作自定义类型的零元素?对于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)
Run Code Online (Sandbox Code Playgroud)
要避免这种问题,请使用array-comprehension来填充它:
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
Run Code Online (Sandbox Code Playgroud)
因此,如果您尝试在元素上进行变异,则会出现错误:
julia> s[1].x
ERROR: UndefRefError: access to undefined reference
in getindex at array.jl:282
Run Code Online (Sandbox Code Playgroud)
一个最小变化的解决方案是使用Points默认构造函数,如下所示:
s[1]=Points(NaN,NaN,NaN)
Run Code Online (Sandbox Code Playgroud)
之后你将能够改变元素s,s[1].x=4.28
其次要有zero的Points类型,你应该添加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)
Run Code Online (Sandbox Code Playgroud)
提示:使用1XN阵列处理ArrayN个元素不是最佳选择,请参阅,Vector{Type}(N)改为使用.