gpt4 book ai didi

tuples - 如何在 Julia 中编写一组元素的外积?

转载 作者:行者123 更新时间:2023-12-05 04:23:11 27 4
gpt4 key购买 nike

一组元素的排列

我有一个 Julia 片段,它生成所有可能的 4 元组,每个槽中有 3 个可能的元素:

julia> collect(Iterators.product(ntuple(_ -> 1:3, 4)...))
3×3×3×3 Array{NTuple{4, Int64}, 4}:
[:, :, 1, 1] =
(1, 1, 1, 1) (1, 2, 1, 1) (1, 3, 1, 1)
(2, 1, 1, 1) (2, 2, 1, 1) (2, 3, 1, 1)
(3, 1, 1, 1) (3, 2, 1, 1) (3, 3, 1, 1)

[:, :, 2, 1] =
(1, 1, 2, 1) (1, 2, 2, 1) (1, 3, 2, 1)
(2, 1, 2, 1) (2, 2, 2, 1) (2, 3, 2, 1)
(3, 1, 2, 1) (3, 2, 2, 1) (3, 3, 2, 1)

[:, :, 3, 1] =
(1, 1, 3, 1) (1, 2, 3, 1) (1, 3, 3, 1)
(2, 1, 3, 1) (2, 2, 3, 1) (2, 3, 3, 1)
(3, 1, 3, 1) (3, 2, 3, 1) (3, 3, 3, 1)

[:, :, 1, 2] =
(1, 1, 1, 2) (1, 2, 1, 2) (1, 3, 1, 2)
(2, 1, 1, 2) (2, 2, 1, 2) (2, 3, 1, 2)
(3, 1, 1, 2) (3, 2, 1, 2) (3, 3, 1, 2)
...

问题

如何修改此代码,而不是对元素使用范围 1:3,而是从数组中选择元素,比如 [1,5],或者一组 Set([1,5]),只有 2 种可能性?

最佳答案

我想这就是您要找的:

julia> original = collect(Iterators.product(ntuple(_ -> [1,5], 4)...))
2×2×2×2 Array{NTuple{4, Int64}, 4}:
[:, :, 1, 1] =
(1, 1, 1, 1) (1, 5, 1, 1)
(5, 1, 1, 1) (5, 5, 1, 1)

[:, :, 2, 1] =
(1, 1, 5, 1) (1, 5, 5, 1)
(5, 1, 5, 1) (5, 5, 5, 1)

[:, :, 1, 2] =
(1, 1, 1, 5) (1, 5, 1, 5)
(5, 1, 1, 5) (5, 5, 1, 5)

[:, :, 2, 2] =
(1, 1, 5, 5) (1, 5, 5, 5)
(5, 1, 5, 5) (5, 5, 5, 5)

julia> flattened = [original...]
16-element Vector{NTuple{4, Int64}}:
(1, 1, 1, 1)
(5, 1, 1, 1)
(1, 5, 1, 1)
(5, 5, 1, 1)
(1, 1, 5, 1)
(5, 1, 5, 1)
(1, 5, 5, 1)
(5, 5, 5, 1)
(1, 1, 1, 5)
(5, 1, 1, 5)
(1, 5, 1, 5)
(5, 5, 1, 5)
(1, 1, 5, 5)
(5, 1, 5, 5)
(1, 5, 5, 5)
(5, 5, 5, 5)

因此,可以简单地用数组或集合代替迭代器。之后,您可以flatten the resulting matrixsplat operator .

此外,这里是如何使用 list comprehensionA[i,j] 形式访问元素的:

julia> original  =  collect(Iterators.product(ntuple(_ -> 1:3, 4)...));
julia> newMatrix = [original[:,:,a,b] for a in 1:3, b in 1:3];

julia> newMatrix[2,3]
3×3 Matrix{NTuple{4, Int64}}:
(1, 1, 2, 3) (1, 2, 2, 3) (1, 3, 2, 3)
(2, 1, 2, 3) (2, 2, 2, 3) (2, 3, 2, 3)
(3, 1, 2, 3) (3, 2, 2, 3) (3, 3, 2, 3)

julia> typeof(newMatrix)
Matrix{Matrix{NTuple{4, Int64}}} (alias for Array{Array{NTuple{4, Int64}, 2}, 2})

关于tuples - 如何在 Julia 中编写一组元素的外积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73777607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com