[英]Making comparisons of a m-dimensional array and an (m-1)-dimensional array repeated along an arbitrary dimension
[英]Defining a multiple-dimensional array of arbitrary dimension in Julia
這個問題與這個有關。
在 Julia 中,我想制作一個 5 x 5 的二維數組,其中 (i, j) 元素具有[i,j]
如下所示:
5×5 Matrix{Vector{Int64}}:
[1, 1] [1, 2] [1, 3] [1, 4] [1, 5]
[2, 1] [2, 2] [2, 3] [2, 4] [2, 5]
[3, 1] [3, 2] [3, 3] [3, 4] [3, 5]
[4, 1] [4, 2] [4, 3] [4, 4] [4, 5]
[5, 1] [5, 2] [5, 3] [5, 4] [5, 5]
我使用數組理解嘗試了這個:
N = 5
L_2 = [[x1,x2] for x1 = 1:N, x2 = 1:N]
我想將這個定義推廣到任意維度D
。
L_1 = [[x1] for x1 = 1:N] # 1-dimensional
L_2 = [[x1,x2] for x1 = 1:N, x2 = 1:N] # 2-dimensional
L_3 = [[x1,x2,x3] for x1 = 1:N, x2 = 1:N,x3 = 1:N] # 3-dimensional
...
#L_D = ??? # D-dimensional
我該如何定義?
不使用數組理解也沒關系。
任何信息,將不勝感激。
您可以概括我在其他答案中發布的vcat
方法,如下所示:
julia> lattice(N, D) = vcat.((reshape(1:N, ntuple(j -> j == i ? N : 1, D)) for i in 1:D)...)
lattice (generic function with 1 method)
julia> lattice(2, 1)
2-element Vector{Vector{Int64}}:
[1]
[2]
julia> lattice(2, 2)
2×2 Matrix{Vector{Int64}}:
[1, 1] [1, 2]
[2, 1] [2, 2]
julia> lattice(2, 3)
2×2×2 Array{Vector{Int64}, 3}:
[:, :, 1] =
[1, 1, 1] [1, 2, 1]
[2, 1, 1] [2, 2, 1]
[:, :, 2] =
[1, 1, 2] [1, 2, 2]
[2, 1, 2] [2, 2, 2]
julia> lattice(2, 4)
2×2×2×2 Array{Vector{Int64}, 4}:
[:, :, 1, 1] =
[1, 1, 1, 1] [1, 2, 1, 1]
[2, 1, 1, 1] [2, 2, 1, 1]
[:, :, 2, 1] =
[1, 1, 2, 1] [1, 2, 2, 1]
[2, 1, 2, 1] [2, 2, 2, 1]
[:, :, 1, 2] =
[1, 1, 1, 2] [1, 2, 1, 2]
[2, 1, 1, 2] [2, 2, 1, 2]
[:, :, 2, 2] =
[1, 1, 2, 2] [1, 2, 2, 2]
[2, 1, 2, 2] [2, 2, 2, 2]
julia> lattice(2, 5)
2×2×2×2×2 Array{Vector{Int64}, 5}:
[:, :, 1, 1, 1] =
[1, 1, 1, 1, 1] [1, 2, 1, 1, 1]
[2, 1, 1, 1, 1] [2, 2, 1, 1, 1]
[:, :, 2, 1, 1] =
[1, 1, 2, 1, 1] [1, 2, 2, 1, 1]
[2, 1, 2, 1, 1] [2, 2, 2, 1, 1]
[:, :, 1, 2, 1] =
[1, 1, 1, 2, 1] [1, 2, 1, 2, 1]
[2, 1, 1, 2, 1] [2, 2, 1, 2, 1]
[:, :, 2, 2, 1] =
[1, 1, 2, 2, 1] [1, 2, 2, 2, 1]
[2, 1, 2, 2, 1] [2, 2, 2, 2, 1]
[:, :, 1, 1, 2] =
[1, 1, 1, 1, 2] [1, 2, 1, 1, 2]
[2, 1, 1, 1, 2] [2, 2, 1, 1, 2]
[:, :, 2, 1, 2] =
[1, 1, 2, 1, 2] [1, 2, 2, 1, 2]
[2, 1, 2, 1, 2] [2, 2, 2, 1, 2]
[:, :, 1, 2, 2] =
[1, 1, 1, 2, 2] [1, 2, 1, 2, 2]
[2, 1, 1, 2, 2] [2, 2, 1, 2, 2]
[:, :, 2, 2, 2] =
[1, 1, 2, 2, 2] [1, 2, 2, 2, 2]
[2, 1, 2, 2, 2] [2, 2, 2, 2, 2]julia> lattice(N, D) = vcat.([reshape(1:N, ntuple(j -> j == i ? N : 1, D)) for i in 1:D]...)
lattice (generic function with 1 method)
julia> lattice(2, 1)
2-element Vector{Vector{Int64}}:
[1]
[2]
julia> lattice(2, 2)
2×2 Matrix{Vector{Int64}}:
[1, 1] [1, 2]
[2, 1] [2, 2]
julia> lattice(2, 3)
2×2×2 Array{Vector{Int64}, 3}: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1, 2, 2, 2] [2, 2, 2, 2, 2]
您似乎不需要 CartesianIndices ,但為了記錄,CartesianIndices 可以采用任何 Int 元組(更准確地說Dims
aka NTuple{N,Int} where N
)來表示數組的大小。 CartesianIndices((5,5))
用於 5x5, CartesianIndices((2,8,3))
用於 2x8x3 等。您可以快速創建 NxNxNx... 表示具有 D 維度的大小的元組NtotheD(N,D) = ntuple(i -> N, D)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.