Julialang:对矩阵列进行就地排序

phi*_*inz 1 performance julia

我有一个巨大的矩阵,并希望对列进行排序以提高速度/内存效率.是否可以对Julia中的矩阵列使用就地排序?例如,采用以下矩阵:

julia> M=Matrix{Int}(3,3);

julia> for i = 1:size(M)[1]
           for j = 1:size(M)[2]
               M[i,j]=3*(j-1)+i
           end
       end

julia> M
3×3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9
Run Code Online (Sandbox Code Playgroud)

我想对列使用就地排序来获取矩阵

3×3 Array{Int64,2}:
 3  6  9
 2  5  8
 1  4  7
Run Code Online (Sandbox Code Playgroud)

这可以在没有就地排序的情况下获得如下:

julia> M_sorted=Matrix{Int}(3,3);

julia> for j = 1:size(M)[2]
           M_sorted[:,j]=sort(M[:,j],rev=true)
       end

julia> M_sorted
3×3 Array{Int64,2}:
 3  6  9
 2  5  8
 1  4  7
Run Code Online (Sandbox Code Playgroud)

但是这样的事情失败了(这里只有一列):

julia> sort!(M[:,1],rev=true)
3-element Array{Int64,1}:
 3
 2
 1

julia> M
3×3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9
Run Code Online (Sandbox Code Playgroud)

在这种情况下,有没有办法使用就地排序?请注意,索引没有问题,因为矩阵在内存中按列保存:

julia> M[1:end]
9-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
 7
 8
 9
Run Code Online (Sandbox Code Playgroud)

所以我认为它应该是可能的.

Chr*_*kas 5

切片会创建列的副本并对其进行排序.如果您想直接在现有数组的内存中进行排序,请使用视图.例:

M=Matrix{Int}(undef,3,3)
for i = 1:size(M)[1]
   for j = 1:size(M)[2]
       M[i,j]=3*(j-1)+i
   end
end

M

3×3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9

sort!(@view(M[:,1]),rev=true)

M

3×3 Array{Int64,2}:
 3  4  7
 2  5  8
 1  6  9
Run Code Online (Sandbox Code Playgroud)