Julia 沿维度展开数组

Julia 沿维度展开数组,julia,Julia,下面的Python函数沿维度展开数组 def expand(x, dim,copies): trans_cmd = list(range(0,len(x.shape))) trans_cmd.insert(dim,len(x.shape)) new_data = x.repeat(copies).reshape(list(x.shape) + [copies]).transpose(trans_cmd) return new_dat

下面的Python函数沿维度展开数组

def expand(x, dim,copies):
        trans_cmd = list(range(0,len(x.shape)))
        trans_cmd.insert(dim,len(x.shape))
        new_data = x.repeat(copies).reshape(list(x.shape) + [copies]).transpose(trans_cmd)
        return new_data

>>x = np.array([[1,2,3],[4,5,6]])
>>x.shape
(2, 3)
>>x_new = expand(x,2,4)
>>x_new.shape
(2,3,4)
>>x_new
array([[[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]],

       [[4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6]]])

如何在Julia中复制此函数?

我不做重复->重塑->置换IMS(就像你在numpy中做的那样),而是做重塑->重复。考虑到行主视图到列主视图的转换,如下所示:

julia> x = [[1,2,3] [4,5,6]]
3×2 Array{Int64,2}:
 1  4
 2  5
 3  6

julia> repeat(reshape(x, (1, 3, 2)), outer=(4,1,1))
4×3×2 Array{Int64,3}:
[:, :, 1] =
 1  2  3
 1  2  3
 1  2  3
 1  2  3

[:, :, 2] =
 4  5  6
 4  5  6
 4  5  6
 4  5  6
在Julia中有效地实现这一点的棘手部分是元组的构造
(1,3,2)
(4,1,1)
。虽然您可以将它们转换为数组并使用数组变异(就像您将其转换为python列表一样),但将它们保留为元组要有效得多
ntuple
这里是您的朋友:

julia> function expand(x, dim, copies)
           sz = size(x)
           rep = ntuple(d->d==dim ? copies : 1, length(sz)+1)
           new_size = ntuple(d->d<dim ? sz[d] : d == dim ? 1 : sz[d-1], length(sz)+1)
           return repeat(reshape(x, new_size), outer=rep)
       end
expand (generic function with 1 method)

julia> expand(x, 1, 4)
4×3×2 Array{Int64,3}:
[:, :, 1] =
 1  2  3
 1  2  3
 1  2  3
 1  2  3

[:, :, 2] =
 4  5  6
 4  5  6
 4  5  6
 4  5  6

julia> expand(x, 2, 4)
3×4×2 Array{Int64,3}:
[:, :, 1] =
 1  1  1  1
 2  2  2  2
 3  3  3  3

[:, :, 2] =
 4  4  4  4
 5  5  5  5
 6  6  6  6

julia> expand(x, 3, 4)
3×2×4 Array{Int64,3}:
[:, :, 1] =
 1  4
 2  5
 3  6

[:, :, 2] =
 1  4
 2  5
 3  6

[:, :, 3] =
 1  4
 2  5
 3  6

[:, :, 4] =
 1  4
 2  5
 3  6
julia>函数展开(x、dim、副本)
sz=尺寸(x)
rep=ntuple(d->d==dim?拷贝数:1,长度(sz)+1)
新的大小=N倍(d->d扩展(x,1,4)
4×3×2数组{Int64,3}:
[:, :, 1] =
1  2  3
1  2  3
1  2  3
1  2  3
[:, :, 2] =
4  5  6
4  5  6
4  5  6
4  5  6
julia>展开(x,2,4)
3×4×2数组{Int64,3}:
[:, :, 1] =
1  1  1  1
2  2  2  2
3  3  3  3
[:, :, 2] =
4  4  4  4
5  5  5  5
6  6  6  6
julia>展开(x,3,4)
3×2×4数组{Int64,3}:
[:, :, 1] =
1  4
2  5
3  6
[:, :, 2] =
1  4
2  5
3  6
[:, :, 3] =
1  4
2  5
3  6
[:, :, 4] =
1  4
2  5
3  6