从Julia Permutions包中获取正则数组



我正在使用置换包来计算一长串输入的逆置换。以下代码产生几乎我想要的:

using Permutations
students = [[3 4 2 1]
[3 4 1 2]
[4 3 2 1]]
students_inv = [Permutation(i)'.data' for i in eachrow(students)]

然后调用students产生

3×4 Array{Int64,2}:
3  4  2  1
3  4  1  2
4  3  2  1

调用CCD_ 2产生

3-element Array{LinearAlgebra.Adjoint{Int64,Array{Int64,1}},1}:
[4 3 1 2]
[3 4 1 2]
[4 3 2 1]

我只想要一个3x4的整数数组,没有所有线性代数的东西。我怎样才能强迫置换给我更简单的输出?

我想您正在寻找mapslicesinvperm:

julia> students = [ 3  4  2  1
3  4  1  2
4  3  2  1 ];
julia> mapslices(invperm, students, dims=2)
3×4 Array{Int64,2}:
4  3  1  2
3  4  1  2
4  3  2  1
julia> using Permutations
julia> mapslices(row -> Permutation(row)'.data, students; dims=2)
3×4 Array{Int64,2}:
4  3  1  2
3  4  1  2
4  3  2  1

请注意,要输入文字矩阵,可以只使用空格和换行符(或分号(,而无需首先单独构造行。

还要注意,使用列而不是行可能更自然。不幸的是,mapslices在大型阵列上运行缓慢。可以这样避免,或者你可能更喜欢全程使用向量向量(或元组向量(,这取决于你在做什么。

julia> reduce(hcat, map(invperm, eachcol(permutedims(students))))
4×3 Array{Int64,2}:
4  3  4
3  4  3
1  1  2
2  2  1

您可以使用vcat函数

julia> students_inv = vcat((Permutation(i)'.data' for i in eachrow(students))...)
3×4 Matrix{Int64}:
4  3  1  2
3  4  1  2
4  3  2  1

假设使用了生成器()表示法,而不是列表理解[]

话虽如此,使用列版本更有效,因为Julia是列主要

julia> students = [[3, 4, 2, 1] [3, 4, 1, 2] [4, 3, 2, 1]]
4×3 Matrix{Int64}:
3  3  4
4  4  3
2  1  2
1  2  1
julia> students_inv = hcat((Permutation(i).data for i in eachcol(students))...)
4×3 Matrix{Int64}:
3  3  4
4  4  3
2  1  2
1  2  1
@btime vcat((Permutation(i)'.data' for i in eachrow($students))...)
#  1.102 μs (26 allocations: 2.31 KiB)
@btime hcat((Permutation(i).data for i in eachcol($students))...)
# 699.378 ns (15 allocations: 1.31 KiB)

最新更新