使用推导式:
julia> [M[m, n] for m in 2:size(M, 1) for n in 1:m-1]
3-element Array{Float64,1}:
0.751
0.734
0.948
但是它比 sundar/Matt B. 的解决方案 慢得多:
lower_triangular_1(M) = [M[m, n] for m in 2:size(M, 1) for n in 1:m-1]
lower_triangular_2(M) = [M[m, n] for n in 1:size(M, 2) for m in n+1:size(M, 1)]
lower_triangular_3(M) = M[tril!(trues(size(M)), -1)]
using BenchmarkTools
using LinearAlgebra
M=rand(100, 100)
使用Julia版本0.7.0-alpha.0
进行测试:
julia> @btime lower_triangular_1(M);
73.179 μs (10115 allocations: 444.34 KiB)
julia> @btime lower_triangular_2(M);
71.157 μs (10117 allocations: 444.41 KiB)
julia> @btime lower_triangular_3(M);
16.325 μs (6 allocations: 40.19 KiB)
虽然不够优雅,但使用@views
可以更快:
function lower_triangular_4(M)
res = similar(M, ((size(M, 1)-1) * size(M, 2)) ÷ 2)
start_idx = 1
for n = 1:size(M, 2)-1
@views column = M[n+1:end, n]
last_idx = start_idx -1 + length(column)
@views res[start_idx:last_idx] = column[:]
start_idx = last_idx + 1
end
end
julia> @btime lower_triangular_4(M);
4.272 μs (101 allocations: 44.95 KiB)