首页 > 解决方案 > 具有不同大小向量的 Julia 数组

问题描述

创建各种大小的向量数组(例如数组)时,我正在生成错误消息。

julia> A = [[1,2] [1,2,3] [1,4] [1] [1,5,6,7]]
ERROR: DimensionMismatch("vectors must have same lengths")
Stacktrace:
 [1] hcat(::Array{Int64,1}, ::Array{Int64,1}, ::Array{Int64,1}, ::Vararg{Array{Int64,1},N} where N) at .\array.jl:1524
 [2] top-level scope at none:0

虽然,如果我初始化一个数组并分配向量“没关系”......

julia> A = Array{Any}(undef,5)
5-element Array{Any,1}:
 #undef
 #undef
 #undef
 #undef
 #undef

pseudo code> A[i] = [x,y...]
2-element Array{Int64,1}:
 1
 2

julia> A
5-element Array{Any,1}:
 [1, 2]
 [1, 2, 3]
 [1]
 [1, 5]
 [1, 2, 6, 4, 5]

有没有办法用不同大小的数组初始化数组,或者 Julia 是否以这种方式配置以防止错误。

标签: julia

解决方案


您用于最外层数组的空格分隔语法专门用于矩阵的水平连接,因此您的代码试图将所有这些向量连接成一个矩阵,这不起作用,因为它们具有不同的长度。在外部数组中使用逗号(如内部数组)来获取数组数组:

julia> A = [[1,2], [1,2,3], [1,4], [1], [1,5,6,7]]
5-element Array{Array{Int64,1},1}:
 [1, 2]
 [1, 2, 3]
 [1, 4]
 [1]
 [1, 5, 6, 7]

推荐阅读