Reputation: 345
When creating an array of various sized vectors(e.g. arrays) I am generating an error msg.
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
Although, if I initalize an array and assign the vectors 'its okay'...
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]
Is there a way to initialize the array with the variously sized arrays or is Julia configured this way to prevent errors.
Upvotes: 4
Views: 1264
Reputation: 33290
The space-separated syntax you're using for the outermost array is specifically for horizontal concatenation of matrices, so your code is trying to concatenate all of these vectors into a matrix, which doesn't work since they have different lengths. Use commas in the outer array like the inner one to get an array of arrays:
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]
Upvotes: 5