【问题标题】:Sortperm for matrix sorting in Julia langSortperm 用于 Julia lang 中的矩阵排序
【发布时间】:2021-07-13 04:28:07
【问题描述】:

我使用的是 Julia 1.6.1。

B 是一个矩阵。例如,

B =
[ 2 4 4 4 5 ;
  1 2 2 3 5 ;
  1 2 3 3 3 ;
  1 2 2 5 6 ;
  1 3 4 4 4 ; ]

我想对每一行进行强制排序。

sortedB = sortslices( B, dims=1, rev=true)

然后,我们得到排序 B

sortedB  =
[ 2 4 4 4 5 ; # 1st row of the original matrix B
  1 3 4 4 4 ; # 5th row of the original matrix B
  1 2 3 3 3 ; # 3rd row of the original matrix B
  1 2 2 5 6 ; # 4th row of the original matrix B
  1 2 2 3 5 ;] # 2nd row of the original matrix B

我想得到数组[1 5 3 4 2]。 我该怎么做?

sortperm 好像不行。

sortperm( sortslices( B, dims=1, rev=true) )
# ERROR: MethodError; no method matching sortperm(::Matrix{Int64})

【问题讨论】:

    标签: sorting matrix julia


    【解决方案1】:

    如果性能有问题,请使用非分配版本。

    julia> sortperm(view.(Ref(B), 1:size(B,1), :), rev=true)
    5-element Vector{Int64}:
     1
     5
     3
     4
     2
    

    这里有一些基准using BenchmarkTools

    julia> @btime sortperm(view.(Ref($B), 1:size($B,1), :),rev=true);
      376.471 ns (3 allocations: 432 bytes)
    
    julia> @btime sortperm(collect(eachslice($B,dims=1)),rev=true)
      642.683 ns (6 allocations: 496 bytes);
    

    【讨论】:

      【解决方案2】:

      您可以使用eachroweachslice

      julia> C = collect(eachslice(B,dims=1))
      5-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
       [2, 4, 4, 4, 5]
       [1, 2, 2, 3, 5]
       [1, 2, 3, 3, 3]
       [1, 2, 2, 5, 6]
       [1, 3, 4, 4, 4]
      
      julia> sortperm(C,rev=true)
      5-element Vector{Int64}:
       1
       5
       3
       4
       2
      

      虽然这将分配超过必要的(collect 显然需要)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 2020-02-23
        • 1970-01-01
        相关资源
        最近更新 更多