如何将Array{Array{Int64,2},1}转换为Array{Int64,2}?

3

在Julia中,我想将定义为2D数组向量的数据转换为矩阵的2D数组。 如下例所示,我想将数据s转换为数据t,但目前尚未成功。 我该怎么处理这种情况?

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

julia> t = [[1 2 3]; [4 5 6]; [7 8 9]]
3××3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

julia> s |> typeof
Array{Array{Int64,2},1}

julia> t |> typeof
Array{Int64,2}

julia> convert(Array{Int64, 2}, s)
ERROR: MethodError: Cannot `convert` an object of type Array{Array{Int64,2},1} to an object of type Array{Int64,2}
This may have arisen from a call to the constructor Array{Int64,2}(...),
since type constructors fall back to convert methods.

julia> reshape(s, 3, 3)
ERROR: DimensionMismatch("new dimensions (3,3) must be consistent with array size 3")
 in reshape(::Array{Array{Int64,2},1}, ::Tuple{Int64,Int64}) at .\array.jl:113
 in reshape(::Array{Array{Int64,2},1}, ::Int64, ::Int64, ::Vararg{Int64,N}) at .\reshapedarray.jl:39

如下例所示,如果您将二维数组或一维数组定义为源数据,我可以成功地将它们重塑为矩阵的二维数组。

julia> u = [1 2 3 4 5 6 7 8 9]
1××9 Array{Int64,2}:
 1  2  3  4  5  6  7  8  9

julia> u |> typeof
Array{Int64,2}


julia> reshape(u, 3, 3)
3××3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9



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

julia> v  |> typeof
Array{Int64,1}

julia> reshape(v, 3, 3)
3××3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9

请参见https://dev59.com/jJffa4cB1Zd3GeqP8HfV。 - mbauman
1个回答

11
你可以使用 vcat 和 splatting
julia> t = vcat(s...)
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

那就是我想要的。谢谢!@pkofod - Masaru Charlie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接