2017-04-21 88 views
3

在Julia中,我想将定义为二维数组Vector的数据转换为Matrix的二维数组。 正如以下示例所述,我想将数据转换为数据t,但目前为止我还没有成功。 我该如何处理案件?如何从Array {Array {Int64,2},1}转换为Array {Int64,2}

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 

如在下面的例子中,如果定义了2D阵列或一维数组作为源数据,然后我可以成功地重塑他们入矩阵的2D阵列。

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 
+0

参见http://stackoverflow.com/questions/37476815/julia-converting-vector-of-arrays-to-array-for-arbitrary -dimensions –

回答

10

您可以使用VCAT和泼洒

julia> t = vcat(s...) 
3×3 Array{Int64,2}: 
1 2 3 
4 5 6 
7 8 9 
+0

这就是我想要的。谢谢! @pkofod, –

+3

你应该把它标记为已回答 –