How to convert a multidimensional array to/from vector of vector of ... vector in julia

时间:2018-01-27 04:59:09

标签: multidimensional-array julia

Is there a method in julia to convert a multidimensional array to a vector of vector and so on, and vice versa? It is OK to define a method for a fix number of dimensions. But how about a method for arbitrary dims?

julia> s = (1,2,3)

julia> a = reshape(1:prod(s), s)
1×2×3 Base.ReshapedArray{Int64,3,UnitRange{Int64},Tuple{}}:
[:, :, 1] =
 1  2

[:, :, 2] =
 3  4

[:, :, 3] =
 5  6

julia> b = [[[a[i,j,k] for i=1:s[1]] for j=1:s[2]] for k=1:s[3]]
3-element Array{Array{Array{Int64,1},1},1}:
 Array{Int64,1}[[1], [2]]
 Array{Int64,1}[[3], [4]]
 Array{Int64,1}[[5], [6]]

julia> unstack(a) == b
ERROR: UndefVarError: unstack not defined

1 个答案:

答案 0 :(得分:2)

RecursiveArrayTools.jl可以帮助完成这类工作。

recs = [rand(8) for i in 1:10]
A = VectorOfArray(recs)
A[i] # Returns the ith array in the vector of arrays
A[j,i] # Returns the jth component in the ith array
A[j1,...,jN,i] # Returns the (j1,...,jN) component of the ith array

因此它就像矩阵一样没有构建矩阵,如果你倾向于对列(它们是独立的数组)进行操作,这是保存分配的好方法。它还可以通过索引回退快速转换为连续数组(老实说,我试图创建一个更快的数据但是后备工作比我能做得更好):

arr = convert(Array,A)

转换回来需要分配课程

VA = VectorOfArray([A[:,i] for i in size(A,2)])