向量的向量访问未定义的引用

时间:2018-08-09 04:13:35

标签: vector julia

我正在尝试创建向量的向量,因为我需要数据结构具有固定数量的行(6)但可变数量的列。在数据结构的每个单元中,我想存储一个结构实例。我的代码是:

struct abc
    a::Float64
    b::Float64
    c
end


k = Vector{Vector{abc}}(6);


for i = 1:6
   for j = 1:6
        aa, bb, cc = i+1, j+1, rand(3);
        instance = abc(aa, bb, cc);
        k[i][j] = instance;
    end
end

我收到此错误:

  

UndefRefError:访问未定义的引用

     

Stacktrace:

     

[1] getindex(:: Array {Array {abc,1},1},:: Int64)在./array.jl:549

     

[2]宏扩展为./In[7]:5 [inlined]

     

[3]在./:处匿名?

你们能告诉我我做错了吗?谢谢!

3 个答案:

答案 0 :(得分:1)

您的变量k尚未初始化其元素。您可以在编写时找到它:

julia> k
6-element Array{Array{abc,1},1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef

最简单的解决方法是使用以下模式:

julia> k = [Vector{abc}(6) for i in 1:6]
6-element Array{Array{abc,1},1}:
 abc[#undef, #undef, #undef, #undef, #undef, #undef]
 abc[#undef, #undef, #undef, #undef, #undef, #undef]
 abc[#undef, #undef, #undef, #undef, #undef, #undef]
 abc[#undef, #undef, #undef, #undef, #undef, #undef]
 abc[#undef, #undef, #undef, #undef, #undef, #undef]
 abc[#undef, #undef, #undef, #undef, #undef, #undef]

现在一切正常。

请注意,在Julia 0.7 / 1.0中,您必须编写k = [Vector{abc}(undef, 6) for i in 1:6](带有undef),以表明您知道您正在创建带有未定义条目的数组。同样,原始代码中的Vector{Vector{abc}}(6)将会失败,您将不得不使用Vector{Vector{abc}}(undef, 6),现在,我认为,很显然内部数组未初始化。

最后,您可以使用以下理解力来一次完成两个步骤:

[[abc(i+1, j+1, rand(3)) for j in 1:6] for i in 1:6]

答案 1 :(得分:1)

声明:

k = Vector{Vector{abc}}(6);

仅初始化大小为6的外部向量,其分量甚至不是大小为零的向量,而只是未定义的结构。 例如:

julia> x=Vector{Vector{Int}}(4)

4-element Array{Array{Int64,1},1}:
 #undef
 #undef
 #undef
 #undef

您可以使用 isssigned 函数检查/是否已分配/定义组件(不触发您在问题中提到的错误):

julia> isassigned(x,2)                 // <---- here

false

julia> x[2]=Vector{Int}(3);

julia> x

4-element Array{Array{Int64,1},1}:
 #undef                                                
    [140512219699984, 140512277526048, 140512217976944]
 #undef                                                
 #undef     

julia> isassigned(x,2)                 // <---- here

true

如果您在施工时知道尺寸,也许最简单的解决方案是使用此方法:

k = [Vector{abc}(5) for i in 1:6]

这将创建一个大小为6的(外部)向量,其所有分量均为大小为5的向量{abc}


更新:回答您的评论。

如果要在以后定义内部矢量大小,我建议初始化零尺寸矢量,然后使用 resize!函数。代码如下:

struct abc end # empty struct, only for demo

k=[Vector{abc}() for i in 1:6]

for i in 1:length(k)
   resize!(k[i],rand(1:6)) # here a random size
   for j in 1:length(k[i])
      # here do what you want with k[i][j]
   end
end 

答案 2 :(得分:1)

尝试:

k = fill(Vector{abc}(),6)
for i = 1:6
   for j = 1:6
        aa, bb, cc = i+1, j+1, rand(3)
        instance = abc(aa, bb, cc)
        push!(k[i], instance)
    end
end

您需要先初始化。